我试着重复 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
为什么会这样?是否有不退回 two-complement representation 的特殊原因? python 中的负整数?
最佳答案
在 Python 中,整数具有任意精度并且它们没有固定大小:-1 的 2 补码表示将需要 1
的无限序列。
关于Python `bin` 负整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802802/