python struct 数字 结构体 例程
#!/usr/bin/python
#-*- coding:utf-8 -*-
import sys
import struct
def simple_test():
trans_id = 0x0001
protocol_id = 0x000
length = 0x0006
unit_id = 01
func_code = 03
start_addr = 0x0000
register_cnt = 0x000a
# 大端
str_format = '>HHHBBHH'
data = struct.pack(str_format, trans_id, protocol_id, length, unit_id, func_code, start_addr, register_cnt)
print 'type(data) =', type(data)
print 'data= ', data
print data.encode('hex')
hex_str = '00000000000601030000000a'
hex_cmd = hex_str.decode('hex')
print hex_cmd
if __name__ == "__main__":
simple_test()
'''
data : 20190704 15:56
modbus tcp
send 12字节:
00 01 事物元标识符
00 00 协议标识符
00 06 长度
01 单元标识符 --- slave id
03 功能码
00 00 起始地址
00 0a 寄存器数量
接收29字节:
00 01 事物元标识符
00 00 协议标识符
00 17 长度
01 单元标识符 --- slave id
03 功能码
14 长度 --- 20字节 -- 对于0x0a个寄存器的值
00 01
00 02
00 03
00 00
00 00
00 00
00 00
00 00
00 00
00 00
'''
log :
C:\Python27\python.exe E:/python/work/thread_t1/struct_test.py
type(data) = <type 'str'>
data=
00010000000601030000000a
Process finished with exit code 0
和 modbus tcp 有关系