Python >> Operator返回的输出与javascript >>>中的输出不同

时间:2019-10-01 03:55:37

标签: javascript python bitwise-operators bit-shift

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在-7910909之后返回了我

使用JavaScript

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

d返回59197955

我可以做些什么来返回与python中javascript相同的值?

1 个答案:

答案 0 :(得分:0)

>>>是不进行符号扩展的,这是您可以在Python中通过将负数转换为正数并使用要处理的位数来获得的效果。因此,对于JavaScript,32位整数和无符号结果,只需在其前而不是后进行屏蔽:

a = -506298134
d = 6
d = (a & 0xFFFFFFFF) >> d
# d == 59197955