Python `bin` 负整数
Python `bin` negative integers
我尝试重复 Brandon Rhodes 的 Pycon2010 演讲 The mighty dictionary 并注意到我无法使用 python 的 bin
内置函数来计算 a 的最低有效位哈希:
>>> 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
内置 returns 位作为带符号的二进制字符串:
>>> bits(-100)
'11111111111111111111111110011100' # two-complement representation preceded by 1s
>>> bin(-100)
'-0b1100100' # signed magnitude representation
为什么会这样?在python中不返回负整数的two-complement representation是否有特殊原因?
在 Python 中,整数具有任意精度并且它们没有固定大小:-1 的 2 补码表示将需要 1
的无限序列。
我尝试重复 Brandon Rhodes 的 Pycon2010 演讲 The mighty dictionary 并注意到我无法使用 python 的 bin
内置函数来计算 a 的最低有效位哈希:
>>> 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
内置 returns 位作为带符号的二进制字符串:
>>> bits(-100)
'11111111111111111111111110011100' # two-complement representation preceded by 1s
>>> bin(-100)
'-0b1100100' # signed magnitude representation
为什么会这样?在python中不返回负整数的two-complement representation是否有特殊原因?
在 Python 中,整数具有任意精度并且它们没有固定大小:-1 的 2 补码表示将需要 1
的无限序列。