Python >> Operator returns different output than in javascript >>>

0
a = -506298134 
d = 6
d = a >> d & 0xFFFFFFFF
d = twos_comp(d, 32)

def twos_comp(val, bits):
    """compute the 2's complement of int value val"""
    if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255
        val = val - (1 << bits)        # compute negative value
    return val

d returns me following -7910909

In Javascript

a = -506298134 
d = 6
d = a >>> d & 0xFFFFFFFF

d returns 59197955

What can I do different to return the same value as javascript in python?

javascript
python
bitwise-operators
bit-shift
asked on Stack Overflow Oct 1, 2019 by Dilli

1 Answer

0

>>> is non-sign-extending, which is an effect you can get in Python by converting a negative number to a positive one with the number of bits you’re working with. So for JavaScript, 32-bit integers and unsigned result, just mask before instead of after:

a = -506298134
d = 6
d = (a & 0xFFFFFFFF) >> d
# d == 59197955
answered on Stack Overflow Oct 1, 2019 by Ry-

User contributions licensed under CC BY-SA 3.0