Python`bin`负整数

我试图重复Brandon Rhodes的Pycon2010 talk
The mighty dictionary并注意到我无法使用python内置的bin来计算哈希的最低有效位:

>>> bin(hash("ftp"))[-3:]
'111'

根据谈话应该是001.

经过一番挖掘后,我发现我必须使用像Brandon这样的自定义位功能:

>>> def bits(integer):
       return "".join(str(x) for x in [1&(integer>>i) for i in range(32)[::-1]])

>>> bits(hash("ftp"))[-3:]
'001'

显然因为内置bin将位返回为具有符号的二进制字符串:

>>> bits(-100)
'11111111111111111111111110011100'  # two-complement representation preceded by 1s
>>> bin(-100)
'-0b1100100'  # signed magnitude representation

为什么会这样?在python中没有返回负整数two-complement representation的特殊原因吗?

最佳答案 在Python中,整数具有任意精度,并且它们没有固定的大小:-1的2补码表示需要1的无限序列.

点赞