Python - 左移和右移长数字给出意想不到的结果

pee*_*pee -1 python bit-shift bitwise-operators python-3.x

我有以下内容

a = 340282366920938463463374607431768211455
b = 127
print(a >> b)
Run Code Online (Sandbox Code Playgroud)

结果值为 1,但我不知道为什么。有什么建议吗?我做得对吗?结果是预期的吗?

具体要求是:

Shift A, right by B, where:

A = 340282366920938463463374607431768211455
B = 127
Run Code Online (Sandbox Code Playgroud)

小智 7

这就是预期的结果。340282366920938463463374607431768211455 是一系列 128 个“1”。如果将其右移 127 位,则其中 127 个“1”将被删除,只剩下“1”。

如果你想看看它的实际效果,请尝试使用 python 的bin()函数,例如

a = 340282366920938463463374607431768211455
b = 127
print(bin(a)) // '0b1111.....'
print(len(bin(a))) // 130 (including '0b', so its actually 128)
print(bin(a >> b)) // '0b1'
Run Code Online (Sandbox Code Playgroud)