# How to get the logical right binary shift in python

Posted on

### Question :

How to get the logical right binary shift in python

As revealed by the title, in JavaScript there is a specific operator `>>>`. For example, in JavaScript we will have the following result:

``````(-1000) >>> 3 = 536870787

(-1000) >> 3 = -125

1000 >>> 3 = 125

1000 >> 3 = 125
``````

So is there a certain method or operator representing this `>>>`?

There isn’t a built-in operator for this, but you can easily simulate the `>>>` yourself:

``````>>> def rshift(val, n): return val>>n if val >= 0 else (val+0x100000000)>>n
...
>>> rshift(-1000, 3)
536870787
>>> rshift(1000, 3)
125
``````

The following alternative implementation removes the need for the `if`:

``````>>> def rshift(val, n): return (val % 0x100000000) >> n
``````

No, there isn’t. The right shift in python is arithmetical.

Numpy provides the `right_shift()` function that does this:

``````>>> import numpy
>>> numpy.right_shift(1000, 3)
125
``````

Here’s a spinoff of aix’s answer. The normal right-shift operator will work if you feed it a positive value, so you’re really looking for a conversion from signed to unsigned.

``````def unsigned32(signed):
return signed % 0x100000000

>>> unsigned32(-1000) >> 3
536870787L
``````

You can do a bitwise shift padding with zeros with the bitstring module using the >>= operator:

``````>>> a = BitArray(int=-1000, length=32)
>>> a.int
-1000
>>> a >>= 3
>>> a.int
536870787
``````

Trying to flip the sign bit of a negative number by masking it with 0x100000000 is fundamentally misconceived as it makes hard assumptions about the word length. In my time as a programmer I have worked with 24-, 48-, 16-, 18-, 32-, 36- and 64-bit numbers. I have also heard of machines that work on odd-lengths, such as 37 and others that use ones-complement, and not twos-complement, arithmetic. Any assumptions you make about the internal representation of numbers, beyond that they are binary, is dangerous.

Even the binary assumption is not absolutely safe, but I think we’ll allow that. đź™‚

You need to remember that if the number is negative, the top bit is set and with each shift right you need to make the top bit set as well.

Here is my implementation:

``````def rshift(val, n):
s = val & 0x80000000
for i in range(0,n):
val >>= 1
val |= s
return val
``````

`>>> def rshift(val,n): return (val>>n) & (0x7fffffff>>(n-1))`