Python之字节到大整数的打包与解包

需求:处理一个拥有128位长的16个元素的字节字符串 

将bytes解析为整数,使用 int.from_bytes() 方法,并像下面这样指定字节顺序:
# 为了将bytes解析为整数,使用 int.from_bytes() 方法,并像下面这样指定字节顺序:
data = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
print(len(data))  # 16
# 如果byteorder为'big',则最重要的字节位于字节数组的开头。 如果byteorder为'little',则最重要的字节位于字节数组的末尾。
print(int.from_bytes(data,"little"))   # 69120565665751139577663547927094891008
print(int.from_bytes(data,"big"))  # 94522842520747284487117727783387188
将一个大整数转换为一个字节字符串,使用 int.to_bytes() 方法,并像下面这样指定字节数和字节顺序:
x=69120565665751139577663547927094891008
# 如果byteorder为'big',则最重要的byte位于字节数组的开头。 如果byteorder为'little',则最重要的byte位于字节数组的末尾。
print(x.to_bytes(16,"little"))   # b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
print(x.to_bytes(16,"big"))   # b'4\x00#\x00\x01\xef\xcd\x00\xab\x90x\x00V4\x12\x00'
试着将一个整数打包为字节字符串
x=523**23
# print(x.to_bytes(16,"little"))   # 报错:OverflowError: int too big to convert
# 解决:int.bit_length() 方法先判断需要多少字节位来存储这个值
print(x.bit_length())   # 208  意思是需要208个字节位存储
nbytes, rem = divmod(x.bit_length(), 8)
print(nbytes, rem)  # 26,0
if rem :
    nbytes+=1
print(nbytes, rem)  # 26,0
print(x.to_bytes(nbytes,"little"))   # b'\x03X\xf1\x82iT\x96\xac\xc7c\x16\xf3\xb9\xcf\x18\xee\xec\x91\xd1\x98\xa2\xc8\xd9R\xb5\xd0'
 
posted on 2019-03-04 17:35  V神丫丫  阅读(877)  评论(0编辑  收藏  举报