2024-06-16 09:29:51 发布
网友
我生成了一个随机的16字节字符串。看起来像这样:
b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\'
我想把它转换成一个(正)整数。在Python中最好的方法是什么?在
我很感激你的帮助。在
一个与python2和python3兼容的解决方案是使用解包结构公司名称:
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)
结果:29853494735036431648325605389381837030L
在python3.2+中,可以使用int.from_bytes():
int.from_bytes()
>>> int.from_bytes(b'\xb68 \xe9L\xbd\x97\xe0\xd6Q\x91c\t\xc3z\\', byteorder='little') 122926391642694380673571917327050487990
您也可以使用'big'字节顺序:
也可以指定是否要使用two的补码表示法。更多信息:https://docs.python.org/3/library/stdtypes.html
一个与python2和python3兼容的解决方案是使用解包结构公司名称:
结果:29853494735036431648325605389381837030L
在python3.2+中,可以使用
int.from_bytes()
:您也可以使用'big'字节顺序:
^{pr2}$也可以指定是否要使用two的补码表示法。更多信息:https://docs.python.org/3/library/stdtypes.html
相关问题 更多 >
编程相关推荐