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
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
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: Returnsxwith the bits shifted to the right byyplaces. This is the same as//'ingxby2**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'
it's right shift operation. One bit right is equivalent to divide by 2.