【问题标题】:Most efficent Way to get lowest 10 bits of a hash as an int in Python在 Python 中将哈希的最低 10 位作为 int 获取的最有效方法
【发布时间】:2014-02-02 21:28:40
【问题描述】:

我正在尝试将 sha256 哈希的前 10 位作为整数获取,目前,我将其转换为字符串,然后将其修剪为 10 位并转换回 int。

这看起来很复杂,有没有更好的方法?

我从这里的另一个帖子中借来的代码

def inttobin(i):
if i == 0:
    return "0"
s = ''
while i:
    if i & 1 == 1:
        s = "1" + s
    else:
        s = "0" + s
    i >>= 1
return s

然后我用来转换为 int 的代码是:

bin = inttobin(struct.unpack('H', hash[:2])[0]) 
idx = int(bin[-10:], 2)

有什么建议吗?

【问题讨论】:

  • 请注意,有一个bin 内置函数可以将整数转换为字符串:即bin(3) -> "0b11"0b 是始终存在的前缀,因此您应该使用bin(x)[2:] 来获得与inttobin 相同的结果。然后表达式简化为int(bin(struct.unpack('H', hash[:2])[0])[-10:], 2)
  • 想必你在这里说的是散列的十六进制摘要
  • 另外:在计算sha256 时,您可以计算digest(),它返回字节。然后在 python3 中你可以做(digest[-2] << 8 + digest[-1]) & 1023。在 python2 中,您必须添加对 ord 的调用。

标签: python binary bit-manipulation


【解决方案1】:

要将某些位提取为整数,可以使用 Python 的"bitwise and", &

对于整数i,前十位是i & 1023 (1023 == (2**10) - 1)。所有高于第十位的位都不在 1023 中,因此将为零。

一个简单的 4 位示例 ((2**4) - 1 == 15):

a = 22 #     10110
b = 15 #      1111
a & b == 6 #  0110

【讨论】:

  • 天才,我从没想过。像魅力一样工作,速度大约是我最初做的方式的两倍。所以我现在有idx = struct.unpack('H', hash[:2])[0] & 1023 非常感谢。
猜你喜欢
  • 1970-01-01
  • 2020-09-07
  • 2016-05-13
  • 2011-06-23
  • 2013-06-16
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多