Bit Level in Matlab

How can we do this bit-level operation in Matlab:

int instructionWord; a = (instructionWord >>> 21) & 0x1F; 

The right right biases the instruction of the command by 21 and receives at least 5 bits. How can this be done in a similar way in Matlab?

+4
source share
3 answers

Given that your input value is an integer, you can do the following:

 a = mod( floor(instructionWord/2^21), 32) 

Another bit solution:

 a = bitand( bitshift(instructionWord, -21), hex2dec('1F')) 

The last method will cause an error if you feed it with something other than intermediaries.

By the way, your commandWord variable is declared as a signed integer. But if it is an instruction word or something like that, an unsigned integer will make more sense. Expressed expressions expect your input to be only positive. Otherwise, you will need a little more code for modeling >>> (logical shift to the right) in matlab.

+5
source

see 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 on how to extract a specific bit value.

+3
source

a = rem (bit-shift (Word instruction, -21), 2 ^ 5)

bithift performs a bit offset; and rem find the remainder of dividing by 32, giving the last value of 5 bits.

+2
source

All Articles