简体   繁体   中英

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.

I'm running into a bug in a graph-based algorithm using the 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).

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.

If a binary represented integer has the most significant bit as "1", then it is considered a negative number.

Read more here:

Two's complement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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