gpt4 book ai didi

python - 如何将摘要的前 n 位转换为整数?

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

我正在使用 Python 3,尝试从 python 的摘要中获取整数。不过,我只对摘要的前 n 位感兴趣。

我现在拥有的是:

n = 3
int(hashlib.sha1(b'test').digest()[0:n])

但这会导致 ValueError: invalidliteral for int() with base 10: b'\xa9J' 错误。

谢谢。

最佳答案

Py3解决方案是使用int.from_bytesbytes 转换为 int,然后移走您不关心的部分:

def bitsof(bt, nbits):
# Directly convert enough bytes to an int to ensure you have at least as many bits
# as needed, but no more
neededbytes = (nbits+7)//8
if neededbytes > len(bt):
raise ValueError("Require {} bytes, received {}".format(neededbytes, len(bt)))
i = int.from_bytes(bt[:neededbytes], 'big')
# If there were a non-byte aligned number of bits requested,
# shift off the excess from the right (which came from the last byte processed)
if nbits % 8:
i >>= 8 - nbits % 8
return i

使用示例:

>>> bitsof(hashlib.sha1(b'test').digest(), 3)
5 # The leftmost bits of the a nibble that begins the hash

在 Python 2 上,除了添加 binascii 导入并将转换从 bytes 更改为 int 之外,该函数几乎可以按原样使用code> 到效率稍低的两步转换(从 str 到十六进制表示,然后使用 intbase 为 16 来解析它):

    i = int(binascii.hexlify(bt[:neededbytes]), 16)

其他一切都按原样工作(甚至 // 运算符也按预期工作;Python 2 的 / 运算符与 Py 3 的不同,但 // 两者的工作原理相同)。

关于python - 如何将摘要的前 n 位转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47086683/

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