how to get last n bits by bit-op?
10,377
Solution 1
This one should work:
mask = (1 << n) - 1
little = num & mask
1
shifted left by n
adds n
zero bits after 1:
>>> bin(0b1 << 4)
'0b10000'
If you subtract 1 from this, you will have a mask that has n
last bits set:
>>> bin((0b1 << 4) - 1)
'0b1111'
Solution 2
Use bits - 1
:
>>> num = 0b111111111
>>> n = 8
>>> bits = 1 << n
>>> num & (bits - 1) # bits - 1 => 0b1111111 because bits is 0b100000000
255
>>> bin(num & (bits - 1))
'0b11111111'
Author by
roger
Updated on June 04, 2022Comments
-
roger almost 2 years
I want to get last n bit of number, for example:
num = 0b111111111 # if I want to get last 8 bits, it will be 0b11111111 # if I want to get last 2 bits, it will be 0b11
I thought this can be ok:
bits = 1 << n little = num & (~bits)
but this is wrong, if n = 8, it get
0b110111111