Files
Python_CookBook_repo/3.数字日期和时间/5.从字符串中打包和解包大整数.py
2025-09-10 16:12:45 +08:00

36 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import struct
import math
if __name__ == '__main__':
# 假如我们有一个用字节串存储的大整数
data = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
# 要将其还原成整数,我们需要:
print(int.from_bytes(data, byteorder="little"))
print(int.from_bytes(data, byteorder="big"))
# 而要将整数转成字节串,我们可以做一个逆向操作
int_to_b = int.from_bytes(data, byteorder="little")
print(int.to_bytes(int_to_b, byteorder="little", length=16))
# 在IPV6中网络地址以一个128位的整数表示这时候我们可以使用struct模块来完成解包
hi, lo = struct.unpack('>QQ', data)
print((hi << 64) + lo)
# 通过byteorder我们可以指定在编成字节码的时候使用大端排序还是小端排序
byte_num = 0x01020304
print(byte_num.to_bytes(4, 'big'))
print(byte_num.to_bytes(4, 'little'))
# 但是请务必使用合适的字节串大小来保存字节串否则python会因为防止信息丢失报错
x = 523**23
try:
x.to_bytes(4, 'little')
except OverflowError:
print("数据溢出")
# 这时候就要先算一下字节长度再行转换
bit_length = x.bit_length()
# 为了让内存结构更加严整我们要将字节串补全成8的整数倍长度
bytes_num = math.ceil(bit_length / 8)
print(x.to_bytes(bytes_num, 'little'))