2025-09-10:仓库迁移
This commit is contained in:
35
3.数字日期和时间/5.从字符串中打包和解包大整数.py
Normal file
35
3.数字日期和时间/5.从字符串中打包和解包大整数.py
Normal file
@@ -0,0 +1,35 @@
|
||||
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'))
|
Reference in New Issue
Block a user