How to get the logical right binary shift in python

dementrock picture dementrock · Apr 29, 2011 · Viewed 33.2k times · Source

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 >>>?

Answer

NPE picture NPE · Apr 29, 2011

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