How can I set fist four bits of a byte to some other specific four bits?
3 views (last 30 days)
Show older comments
If I have an array of nx1 and I want to set first four bits of each byte of an array to some other specific 4 bits so how to perform this using bitset command or is there any other command to perform this??
0 Comments
Answers (1)
Image Analyst
on 13 Apr 2013
You can use bitor() and bitand(). Try this demo:
% Pick a number.
value = 44
dec2bin(value)
% Let's define bits to set. 1 means set, 0 means leave alone.
bitsToSet = '00010011'
numberToOr = bin2dec(bitsToSet)
% Let's "OR" the number with our original "value"
% to get bits 4, 1, and 0 to be 1
newValue = bitor(value, numberToOr)
% Let's look at the bits of the new value.
dec2bin(newValue)
% Now clear bits 5, 3, and 1. 0 means clear, 1 means leave alone.
bitsToClear = '11010101' % 0 means clear that bit.
numberToAnd = bin2dec(bitsToClear)
% Let's "AND" the number with our new "value"
% to get bits 5, 3, and 1 to be 1
newValue = bitand(newValue, numberToAnd)
% Let's look at the bits of the new value.
dec2bin(newValue)
In the command window:
value =
44
ans =
101100
bitsToSet =
00010011
numberToOr =
19
newValue =
63
ans =
111111
bitsToClear =
11010101
numberToAnd =
213
newValue =
21
ans =
10101
8 Comments
Image Analyst
on 14 Apr 2013
If we're done, then please officially mark the answer as Accepted. Thanks.
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!