Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get last n bits by bit-op?

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

like image 951
roger Avatar asked Mar 21 '16 06:03

roger


People also ask

How do I extract a bit in Python?

*/ Step 1 : first convert the number into its binary form using bin(). Step 2 : remove the first two character. Step 3 : then extracting k bits from starting position pos from right.so, the ending index of the extracting substring is e=len(bi)-pos and starting index=e-k+1 Step 4 : extract k bit sub-string.


1 Answers

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'
like image 161