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

标签 python python-3.x digest

我正在使用 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/

相关文章:

HTTP 摘要认证 MD5 冲突

Tensorflow 中的 Python SSL 认证问题

python - super() 和直接调用父类(super class)的区别

python - 类型错误 : method() takes 1 positional argument but 2 were given

python - 在 Dataframe 的句子中查找多个单词并转换为分数的总和

ruby - 尝试存储临时文件时的 Aws::S3::Errors::BadDigest

python - 使用 CSV.QUOTE_NONNUMERIC 而不引用标题

python - 在 Google Cloud ML Engine 中使用自定义依赖项

python - 严格比较

ruby - 摘要的 Base-36 表示