码迷,mamicode.com
首页 > 其他好文 > 详细

struct模块

时间:2020-02-03 14:09:39      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:一个   有一个   tle   alignment   没有   pac   and   long   pre   

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‘@\xe2\x01\x00‘
4
123456

struct模块

标签:一个   有一个   tle   alignment   没有   pac   and   long   pre   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!