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

Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197

2 Answers2

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'
msvalkon
  • 11,417
  • 2
  • 39
  • 37
1

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

venpa
  • 4,060
  • 19
  • 23