Python`bin`负整数

时间:2015-11-19 11:35:38

标签: python hash binary built-in

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

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

根据谈话应该是001

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

>>> 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

1 个答案:

答案 0 :(得分:2)

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