Python `bin` 负整数

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

为什么会这样?是否有不退回 two-complement representation 的特殊原因? python 中的负整数?

最佳答案

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

关于Python `bin` 负整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802802/

相关文章:

C++ 问号输出

python - Unicode解码错误 : 'charmap' codec| Error during installation of pip python-stdnum==1. 8

python - 如何使用pyspark在s3上获取csv(方案: s3n)没有文件系统

python - 日内时间序列的多指数结构(10 分钟价格数据)

performance - 哈希表 - 为什么它比数组快?

c - 在 C 中以十六进制级别拆分 int?

python - 层 lstm_5 的输入 0 与层 : expected ndim=3, 不兼容,发现 ndim=2

python - 优化 3d 点哈希函数

python - 为什么可以将bcrypt.hashpw同时用于哈希和验证密码?

c# - 将十六进制字符串转换为二进制字符串 C#