# struct - 格式符
# -------------------------------------------------------------------------------
# FORMAT C-TYPE PYTHON-TYPE STANDARD-SIZE NOTES
# -------+--------------------+---------------------+---------------+------------
# x pad byte no value
# c char string of length 1 1
# b signed char integer 1 (3)
# B unsigned char integer 1 (3)
# ? _Bool bool 1 (1)
# h short integer 2 (3)
# H unsigned short integer 2 (3)
# i int integer 4 (3)
# I unsigned int integer 4 (3)
# l long integer 4 (3)
# L unsigned long integer 4 (3)
# q long long integer 8 (2), (3)
# Q unsigned long long integer 8 (2), (3)
# f float float 4 (4)
# d double float 8 (4)
# s char[] string
# p char[] string
# P void * integer (5), (3)
# -------------------------------------------------------------------------------
# 注1.q和Q只在机器支持64位操作时有意思
# 注2.每个格式前可以有一个数字,表示个数
# 注3.s格式表示一定长度的字符串,4s表示长度为4的字符串,但是p表示的是pascal字符串
# 注4.P用来转换一个指针,其长度和机器字长相关
# 注5.最后一个可以用来表示指针类型的,占4个字节
# -------------------------------------------------------------------------------
# struct - 对齐方式
# --------------------------------------------------------------
# CHARACTER BYTE-ORDER SIZE ALIGNMENT
# ------------+--------------------------+----------+-----------
# @ native native native
# = native standard none
# < little - endian standard none
# > big - endian standard none
# ! network( = big - endian) standard none
# --------------------------------------------------------------
# struct - 例子
#
# struct Header
# {
# unsigned short id;
# char[4] tag;
# unsigned int version;
# unsigned int count;
# }
#
# st = struct.pack("!H4s2I", id , tag, version, count); # 打包struct
# tup = struct.unpack("!H4s2I", data) # 解析成tuple
# id, tag, version, count = struct.unpack("!H4s2I", data) # 解析成员变量
# id = int.from_bytes(data[0:1], byteorder='big', signed=False) # bytes转int
Python:struct处理二进制数据bytes。
于 2022-04-06 11:38:24 首次发布