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中:
is 2Byte==Short=transaction
H
标识符是2Byte==Short=
H
is 2Byte==Short=length
H
是1字节==unitid
B
是1字节==fcode
B
is 2Byte==Short=reg_addr
H
is 2Byte==Short=count
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测试这些代码片段
- 您还可以在中检查这些代码段李>
- 但是,如果遇到
错误,请使用withstruct.error:required参数不是整数
int(,16)
int(hex,16)
tostruct.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'