使用结构包字符串值的格式

2024-03-28 12:53:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我想查看我的数据包格式:b'\x00\x01\x00\x00\x00\x06

但我看到的是这样的格式:\x00\x01\x06\x01\x03\我怎么看这个?在

encoder=struct.pack('5B',int(trnsact,16),int(ident,16),int(length_data,16),int(unitid,16),int(func_code,16))

这就是我的价值观:

^{pr2}$

type(transaction_id)=string(因此我将字符串值转换为整数)

如果我使用这种类型:

encoder=struct.pack('5B',transaction,ident,unitid,funcode)

我有这个错误:struct.error: required argument is not an integer

我对此很困惑请帮帮我 在


Tags: encoder格式数据包lengthstructpackinttransaction
1条回答
网友
1楼 · 发布于 2024-03-28 12:53:06

在Modbus TCP中:

  • transaction是2Byte==Short==H
  • identifier是2Byte==Short==H
  • length是2Byte==Short==H
  • unitid是1字节==B
  • fcode是1字节==B
  • reg_addr是2Byte==Short==H
  • count是2Byte==Short==H

因此,在您的案例中,格式将是>HHHBB或{}:

import struct

transaction = 0x00
ident = 0x01
length_data = 0x06
unitid = 0x01
fcode = 0x03

encoder = struct.pack('>HHHBB', transaction, ident, length_data, unitid, fcode)
print(encoder)

输出:

^{pr2}$

[更新]:

不管怎样,如果您想这样(b'\x00\x01\x00\x00\x00\x06),请按以下步骤操作:

import struct

transaction = 0x00  # Used with replacement.
ident = 0x01  # Used with replacement.
length_data = 0x06  # Used.
unitid = 0x01  # Not used.
fcode = 0x03  # Not used.

encoder = struct.pack('>3H', ident, transaction, length_data)
print(encoder)

输出:

b'\x00\x01\x00\x00\x00\x06'

[注意]:

  • B是无符号字节。在
  • H是无符号短的。在
  • <是Little-Endian。在
  • >是Big-Endian。

  • 我用Python2.7和Python3.6测试这些代码片段。

  • 您也可以在Python3_online_IDE中检查这些代码片段。在
  • 但是,如果遇到struct.error: required argument is not an integer错误,请使用with int(<hex-str>, 16)

相关问题 更多 >