Python struct使用简介
程序员文章站
2022-07-10 08:29:12
...
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version: v1.0
# @author: payne fu
# @email: [email protected]
# @file name: test.py
# @created time: 2019/11/20 14:31
import struct
import struct
# 详细使用方法:https://docs.python.org/3.7/library/struct.html?highlight=struct#struct.pack
hex_str = "1672824A4925"
print(bytes.fromhex(hex_str))
# No padding is added when using non-native size and alignment, e.g. with ‘<’, ‘>’, ‘=’, and ‘!’.
# 如:下例会返回8,虽然h占2字节,i占4字节,但由于默认用的native size,所以h会被填充2字节来对齐
print(struct.calcsize('hi'))
# 如:下例会返回6,没有填充,=表示非native size
print(struct.calcsize('=hi'))
# 下面会报错,因为参数2只有6字节 # struct.error: unpack requires a buffer of 8 bytes
# print(struct.unpack("hi", bytes.fromhex(hex_str)))
# 下面才会正常打印
print(struct.unpack("=hi", bytes.fromhex(hex_str)))
# 假如C语言有结构体如下:
"""
struct test {
int i;
int j;
short m;
float n;
};
"""
# 如何将Python数据的数据转化成C语言以上结构体数据呢?通过Python struct的pack方法
i = 1; j = 2; m = 3; n = 4.5
c_data = struct.pack('=iihf', i, j, m, n)
print(c_data)
# 又如何将C语言以上结构体数据转换成Python数据呢? 通过Python struct的unpack方法
print(struct.unpack('=iihf', c_data))
下一篇: Chrome书签被篡改之后的恢复
推荐阅读
-
Python3.4 splinter(模拟填写表单)使用方法
-
Python机器学习库scikit-learn安装与基本使用教程
-
python之super的使用小结
-
turtle的基础使用之python turtle递归绘图
-
Python使用itchat获取微信好友
-
python使用Plotly绘图工具绘制水平条形图
-
python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
-
使用Python在Excel中嵌入附件(txt文件,zip压缩包)对象
-
Python字符串内置函数使用
-
OpenCV中的新函数connectedComponentsWithStats使用(python和c++实例)