Python`bin`负整数

2024-09-28 21:50:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

根据谈话应该是001。在

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

^{pr2}$

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

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

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


Tags: the函数dictionarybinftphash内置bits