36 lines
1.4 KiB
Python
36 lines
1.4 KiB
Python
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'))
|