#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version: v1.0
# @author: payne fu
# @email: bbccaaac@163.com
# @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))