struct模块

struct模块

把一个数字打包成固定长度的4字节

Format C Type Python Notes
x pad byte no value
c char string of length 1
b signed char integer
B unsigned char integer
? _Bool bool (1)
h short integer
H unsigned short integer
i int integer
I unsigned int integer or long
l long integer
L unsigned long long
q long long long (2)
Q unsigned long long long (2)
f float float
d double float
s char[] string
p char[] string
P void * long

在Format string 的首位,有一个可选字符来决定大端和小端,列表如下:

Character Byte order Size and alignment
@ native native
= native standard
< little-endian standard
> big-endian standard
! network (= big-endian) standard

如果没有附加,默认为@,即使用本机的字符顺序(大端or小端),对于C结构的大小和内存中的对齐方式也是与本机相一致的(native),比如有的机器integer为2位而有的机器则为四位;有的机器内存对其位四位对齐,有的则是n位对齐(n未知,我也不知道多少)。

# 把一个数字打包成固定长度的4字节
obj = struct.pack('i', 123456)
print(obj)
print(len(obj))

res = struct.unpack('i', obj) # 返回元组
print(res[0])

b'@xe2x01x00'
4
123456

原文地址:https://www.cnblogs.com/randysun/p/12255237.html