How to strip off left side of binary number in Python?
Question:
I got this binary number 101111111111000
I need to strip off the 8 most significant bits and have 11111000
at the end.
I tried to make 101111111111000 << 8
, but this results in 10111111111100000000000
, it hasn’t the same effect as >>
which strips the lower bits. So how can this be done? The final result MUST BE binary type.
Answers:
You can get the rightmost 8 bits of an integer n
using bitwise-and:
n&255
255 is the sum of the values of the smallest 8 bits.
So, starting with 101111111111000
, which is 24568 decimal, n&255
gives 11111000
, which is 248 decimal.
To achieve this for a number x
with n
digits, one can use this
x&(2**(len(bin(x))-2-8)-1)
-2 to strip 0b, -8 to strip leftmost
Simply said it ands
your number with just enough 1
s that the 8 leftmost bits are set to 0.
another general way to do this is:
n = int('101111111111000', 2) # 24568
n & (1 << int.bit_length(n) - 8) - 1
gives 120 (or 1111000
)
Another general way:
x&(2**n-1)
where x
is the integer and n
is the number of bits you want to strip.
I got this binary number 101111111111000
I need to strip off the 8 most significant bits and have 11111000
at the end.
I tried to make 101111111111000 << 8
, but this results in 10111111111100000000000
, it hasn’t the same effect as >>
which strips the lower bits. So how can this be done? The final result MUST BE binary type.
You can get the rightmost 8 bits of an integer n
using bitwise-and:
n&255
255 is the sum of the values of the smallest 8 bits.
So, starting with 101111111111000
, which is 24568 decimal, n&255
gives 11111000
, which is 248 decimal.
To achieve this for a number x
with n
digits, one can use this
x&(2**(len(bin(x))-2-8)-1)
-2 to strip 0b, -8 to strip leftmost
Simply said it ands
your number with just enough 1
s that the 8 leftmost bits are set to 0.
another general way to do this is:
n = int('101111111111000', 2) # 24568
n & (1 << int.bit_length(n) - 8) - 1
gives 120 (or 1111000
)
Another general way:
x&(2**n-1)
where x
is the integer and n
is the number of bits you want to strip.