对字符串值使用Struct.pack格式

时间:2018-11-01 08:10:08

标签: python python-3.x struct

我想用以下格式查看我的数据包: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))

那是我的价值观:

transaction_id=0x00
ident_id=0x01
length_data=0x06
unitid=0x01
funccode=0x03

还有type(transaction_id)=string(所以我将我的字符串值变成了整数)

如果我使用这种类型:

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

我遇到此错误:struct.error: required argument is not an integer

对此我很困惑,请帮助我

1 个答案:

答案 0 :(得分:0)

在Modbus-TCP中:

  • transaction是2Byte ==短== H
  • identifier是2Byte ==短== H
  • length是2Byte ==短== H
  • unitid是1Byte == B
  • fcode是1Byte == B
  • reg_addr是2Byte ==短== H
  • count是2Byte ==短== H

因此,您使用的格式为>HHHBB>3H2B

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)

出局:

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

[更新]:

无论如何,如果您想要这样(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。
  • >是大尾数法。

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

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