Rodrigo Formighieri
Rodrigo Formighieri

Reputation: 477

How to strip off left side of binary number in Python?

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.

Upvotes: 0

Views: 1923

Answers (4)

Adam Jenča
Adam Jenča

Reputation: 585

Another general way:

x&(2**n-1)

where x is the integer and n is the number of bits you want to strip.

Upvotes: 0

Sam Mason
Sam Mason

Reputation: 16174

another general way to do this is:

n = int('101111111111000', 2) # 24568

n & (1 << int.bit_length(n) - 8) - 1

gives 120 (or 1111000)

Upvotes: 1

Jonathan R
Jonathan R

Reputation: 3928

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 1s that the 8 leftmost bits are set to 0.

Upvotes: 0

khelwood
khelwood

Reputation: 59096

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.

Upvotes: 5

Related Questions