I got this binary number
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:
255 is the sum of the values of the smallest 8 bits.
So, starting with
101111111111000, which is 24568 decimal,
11111000, which is 248 decimal.
To achieve this for a number
n digits, one can use this
-2 to strip 0b, -8 to strip leftmost
Simply said it
ands your number with just enough
1s 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
Another general way:
x is the integer and
n is the number of bits you want to strip.