gpt4 book ai didi

python - 在 Python 中获取哈希的最低 10 位作为 int 的最有效方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:18 25 4
gpt4 key购买 nike

我正在尝试将 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)

有什么建议吗?

最佳答案

要将某些位提取为整数,您可以使用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

关于python - 在 Python 中获取哈希的最低 10 位作为 int 的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21120022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com