end
dec
dec = uint8
205
dec2bin(dec)
ans =
'11001101'
Reading Consecutive Bits
Another use of bit shifting is to isolate consecutive sections of bits. For example, read the last four
bits in the 16-bit number 0110000010100000. Recall that the last four bits are on the left of the
binary representation.
n = 0b0110000010100000;
dec2bin(bitshift(n,-12))
ans =
'110'
To isolate consecutive bits in the middle of the number, you can combine the use of bit shifting with
logical masking. For example, to extract the 13th and 14th bits, you can shift the bits to the right by
12 and then mask the resulting four bits with 0011. Because the inputs to bitand must be the same
integer data type, you can specify 0011 as an unsigned 16-bit integer with 0b11u16. Without the -
u16 suffix, MATLAB stores the number as an unsigned 8-bit integer.
m = 0b11u16;
dec2bin(bitand(bitshift(n,-12),m))
ans =
'10'
Another way to read consecutive bits is with bitget, which reads specified bits from a number. You
can use colon notation to specify several consecutive bits to read. For example, read the last 8 bits of
n.
bitget(n,16:-1:8)
ans = 1x9 uint16 row vector
0
1
1
0
0
0
0
0
1
Reading Nonconsecutive Bits
You can also use bitget to read bits from a number when the bits are not next to each other. For
example, read the 5th, 8th, and 14th bits from n.
bits = [14 8 5];
bitget(n,bits)
ans = 1x3 uint16 row vector
2 Program Components
2-42
Précédent

- 92/1450

Suivant