【问题标题】:Convert 16 bytes of random data to integer in Python在 Python 中将 16 个字节的随机数据转换为整数
【发布时间】:2017-03-05 14:22:45
【问题描述】:

我生成了一个随机的 16 字节字符串。它看起来像这样:

b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\'

我想将其转换为(正)整数。在 Python 中执行此操作的最佳方法是什么?

感谢您的帮助。

【问题讨论】:

  • 它的预期字节序是什么?
  • @Logan 我也看到了那个帖子,但我不明白为什么要使用结构?这不可能是解决方案。
  • @kindall Little Endian

标签: python string random binary int


【解决方案1】:

在 Python 3.2+ 中,您可以使用int.from_bytes()

>>> int.from_bytes(b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\', byteorder='little')
122926391642694380673571917327050487990

您也可以使用“大”字节序:

>>> int.from_bytes(b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\', byteorder='big')
242210931377951886843917078789492013660

您还可以指定是否要使用二进制补码表示。欲了解更多信息:https://docs.python.org/3/library/stdtypes.html

【讨论】:

  • 哦,我想这正是我需要的。如果我的数据是随机的,我认为使用小端或大端无关紧要,它只会打乱数字,对吧?
  • 我想这取决于您计划对整数做什么,但是是的,如果您更改字节顺序,数字会有所不同。
  • 从那个号码返回原始字符串的命令是什么?
  • 看起来你可以使用 int.to_bytes():docs.python.org/3/library/stdtypes.html#int.to_bytes
【解决方案2】:

同时兼容 Python 2 和 Python 3 的解决方案是使用 struct.unpack:

import struct
n = b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\'
m = struct.unpack("<QQ", n)
res = (m[0] << 64) | m[1]
print(res)

结果:298534947350364316483256053893818307030L

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 2014-04-14
    相关资源
    最近更新 更多