Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit level operation in Matlab

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?

like image 879
Shan Avatar asked Dec 26 '22 09:12

Shan


2 Answers

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.

like image 139
KlausCPH Avatar answered Dec 28 '22 23:12

KlausCPH


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.

like image 36
memyself Avatar answered Dec 28 '22 23:12

memyself