(-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
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
def rshift(val, n): return (val % 0x100000000) >> n
No, there isn’t. The right shift in python is arithmetical.
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
int=-1000, length=32) a.int -1000 a >>= 3 a.int 536870787a = BitArray(
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
A solution that works without a modulo:
>>> def rshift(val,n): return (val>>n) & (0x7fffffff>>(n-1))
This works since 7fffffff is a positive number and right shifting that will add zeros to the left.