How to get the logical right binary shift in python

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

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


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