简体   繁体   English

python - 正整数上的位移产生负整数......怎么会发生这种情况?

[英]python - bit shift on positive integer producing negative integer … how could this happen?

I've created a Python 3 BitSet class that I'm using for fast set operations on the domain of integers starting at 0. 我已经创建了一个Python 3 BitSet类,我用它来从0开始的整数域上进行快速设置操作。

I'm running into a bug in a graph-based algorithm using the BitSet. 我正在使用BitSet在基于图形的算法中遇到一个错误。 My debugging code 我的调试代码

print(v)
print(v == 63)
print(1 << v)

produces the following output (note the sign on the final line): 产生以下输出(注意最后一行的符号):

63
True
-9223372036854775808

When I try the following in the interpreter, I get the positive answers I'm looking for: 当我在翻译中尝试以下内容时,我得到了正在寻找的正面答案:

>>> 1 << 63
9223372036854775808
>>> x = 1 << 61 | 1 << 63
>>> x
11529215046068469760
>>> bin(x)
'0b1010000000000000000000000000000000000000000000000000000000000000'

One clue is that the first place this code produces a bug is close to the sys.maxsize for my system (9223372036854775807, or 2^63 - 1). 一个线索是,此代码产生错误的第一个位置接近我的系统的sys.maxsize(9223372036854775807,或2 ^ 63 - 1)。

Any thoughts on what could cause this behavior? 有什么可能导致这种行为的想法?

What I've tried so far 到目前为止我尝试过的

I've tried to read everything possible on integer overflow, etc. I wouldn't have thought that Python 3 (with it's arbitrary-length integers) would generate this kind of error. 我试图在整数溢出等上读取所有可能的内容。我不会认为Python 3(使用它的任意长度整数)会产生这种错误。

If a binary represented integer has the most significant bit as "1", then it is considered a negative number. 如果二进制表示的整数具有最高有效位为“1”,则将其视为负数。

Read more here: 在这里阅读更多:

Two's complement 两个补码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM