aed*_*duG 3 python string random binary int
我生成了一个随机的 16 字节字符串。它看起来像这样:
b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\'
Run Code Online (Sandbox Code Playgroud)
我想将其转换为(正)整数。在 Python 中执行此操作的最佳方法是什么?
我很感激你的帮助。
在 Python 3.2+ 中,您可以使用int.from_bytes():
>>> int.from_bytes(b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\', byteorder='little')
122926391642694380673571917327050487990
Run Code Online (Sandbox Code Playgroud)
您还可以使用“大”字节顺序:
>>> int.from_bytes(b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\', byteorder='big')
242210931377951886843917078789492013660
Run Code Online (Sandbox Code Playgroud)
您还可以指定是否要使用二进制补码表示形式。欲了解更多信息:https ://docs.python.org/3/library/stdtypes.html