How to get the logical right binary shift in pytho

2019-02-02 10:00发布

问题:

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

回答1:

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


回答2:

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



回答3:

Numpy provides the right_shift() function that does this:

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


回答4:

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


回答5:

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. :)



回答6:

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


回答7:

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