2

Hello I was writing a decimal to binary function and I found this code that works perfectly:

while n > 0:
    b = str(n % 2) + b
    n >>= 1

However I do not know what >>= does could you enlighten me?

Many thanks

2

2 Answers 2

2

It's a binary right shift operation. The bits in n are shifted to the right by 1. It's equivalent of saying n = n >> 1.

From BitwiseOperators in python:

x >> y: Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.

For instance, assume an integer 4 and let's shift it to the right by 1 places.

 # First let's look at what 4 is in binary.
 >>> bin(4)[2:].zfill(8) # this pads to 8 bits.
 '00000100'

 # If you shift all the bits towards the right 1 places the result is
 # '00000010', which in turn is 2 in base 10.
 >>> 4 >> 1
 2

 >>> bin(2)[2:].zfill(8)
 '00000010'
Sign up to request clarification or add additional context in comments.

Comments

1

it's right shift operation. One bit right is equivalent to divide by 2.

1 Comment

indeed purpose here of >>= is divide by 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.