How can I set fist four bits of a byte to some other specific four bits?
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??
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
Sana Shaikh
on 13 Apr 2013
Sana Shaikh
on 13 Apr 2013
Image Analyst
on 13 Apr 2013
Edited: Image Analyst
on 13 Apr 2013
value = 149; % '10010101'
% Let's look at the bits of the value.
dec2bin(value)
% Zero out left 4 bits by ANDing with '0000 1111' (15)
% Set left 4 bits by ORing with '0010 0000' (32)
newValue = bitor(32,bitand(value, 15))
% Let's look at the bits of the new value.
dec2bin(newValue)
Sana Shaikh
on 13 Apr 2013
Edited: Sana Shaikh
on 13 Apr 2013
Sana Shaikh
on 13 Apr 2013
Edited: Sana Shaikh
on 13 Apr 2013
Image Analyst
on 13 Apr 2013
Of course it works just in that case. Each time you have a new bit pattern you want to set, you have to change the numbers you AND and OR with. But that makes sense.
I don't know what your function bitsliceget is- it's not in my toolboxes.
Sana Shaikh
on 14 Apr 2013
Image Analyst
on 14 Apr 2013
If we're done, then please officially mark the answer as Accepted. Thanks.
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!