How can we do this bit level operation in Matlab:
int instructionWord;
a = (instructionWord >>> 21) & 0x1F;
The code right shifts the instructionWord by 21 and obtains the least 5 bits. How can this be equivalently done in Matlab?
Given that your input value is an integer, you could do the following:
a = mod( floor(instructionWord/2^21), 32)
Another more bit-like solution would be:
a = bitand( bitshift(instructionWord, -21), hex2dec('1F'))
The last method will throw an error if you feed it anything else than intergers.
By the way, your variable instructionWord is declared like a signed integer. But if it is an instruction word or something like that, an unsigned integer would make more sense. The expressions above expect that your input is only positive. If not, it will require a bit more code to model the >>>
(logical right-shift) in matlab.
see the bitshift page:
Code
a = intmax('uint8');
s1 = 'Initial uint8 value %5d is %08s in binary\n';
s2 = 'Shifted uint8 value %5d is %08s in binary\n';
fprintf(s1,a,dec2bin(a))
for i = 1:8
a = bitshift(a,1);
fprintf(s2,a,dec2bin(a))
end
Output
Initial uint8 value 255 is 11111111 in binary
Shifted uint8 value 254 is 11111110 in binary
Shifted uint8 value 252 is 11111100 in binary
Shifted uint8 value 248 is 11111000 in binary
Shifted uint8 value 240 is 11110000 in binary
Shifted uint8 value 224 is 11100000 in binary
Shifted uint8 value 192 is 11000000 in binary
Shifted uint8 value 128 is 10000000 in binary
Shifted uint8 value 0 is 00000000 in binary
EDIT see bitget page on how to extract a specific bit value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With