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

Python 对字符串值使用Struct.pack格式,python,python-3.x,struct,Python,Python 3.x,Struct,我想以以下格式查看我的数据包:b'\x00\x01\x00\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_

我想以以下格式查看我的数据包:
b'\x00\x01\x00\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\u id)=string
(因此我将我的字符串值转换为整数)

如果我使用此类型:

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

我有以下错误:
struct.error:必需的参数不是整数

我对此很困惑,请帮帮我 在Modbus TCP中:

  • transaction
    is 2Byte==Short=
    H
  • 标识符是2Byte==Short=
    H
  • length
    is 2Byte==Short=
    H
  • unitid
    是1字节==
    B
  • fcode
    是1字节==
    B
  • reg_addr
    is 2Byte==Short=
    H
  • count
    is 2Byte==Short=
    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\x01\x00\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
    是无符号字节
  • H
    为无符号短字符
  • 是Big-Endian

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

  • 您还可以在中检查这些代码段
  • 但是,如果遇到
    struct.error:required参数不是整数
    错误,请使用with
    int(,16)

我更新了我的答案,并在Python3.6中进行了检查,没有任何错误。你可以试试这个。我用
int(hex,16)
to
struct.pack()
来处理错误,这很混乱!检查这个问题,似乎是同样的问题。如果你的问题解决了我的答案,请考虑表决到它:
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'