How can I set fist four bits of a byte to some other specific four bits?

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)

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

Actually I want to replace the first four bits with some other four bits.
if a= 10010101 in binary then I want to replace first four bits i-e 1001 with bits of my own let say 0010. How can I ?
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)
well, this will work but just in this case (if I m not wrong)
My prob is:
I have,
new=fi(bin2dec(shifted),0,8,0); %value of new 150738x1 embedded.fi
bits8to5 = fi(bitsliceget(new,8,5),0,4,0);
bits4to1 = fi(bitsliceget(new,4,1),0,4,0);
XORED=fi(bitxor(bits8to5,bits4to1),0,4,0);
Now I want to replace the first 4 bits(i-e from bit8 to bit5) of "new" with the XORED bits.
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.
If we're done, then please officially mark the answer as Accepted. Thanks.

Sign in to comment.

Categories

Asked:

on 13 Apr 2013

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!