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
*/ 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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With