简体   繁体   English

将字符串转换为字节时遇到问题

[英]Having Trouble converting a string to bytes

I'm trying to convert a string to a byte, thats what I've done.我正在尝试将字符串转换为字节,这就是我所做的。
I want to send out a Modbusprotocol via serial and put it together in bitstring:我想通过串行发送一个 Modbus 协议并将其放在位串中:

tiger = '01' 
read = '03'
ac_val = '0031'
word = '0002'

code = tiger+read+ac_val+word
print(code)
010300310002

#now i want to put thist string in a bitstring with the function:

codeh = bytes.fromhex(code)
codeh = b'\x01\x03\x001\x00\x02 #This is what i got

But i was expecting:但我期待:

codeh = b'\x01\x03\x00\x31\x00\x02

I have no idea why the output is like this.我不知道为什么output是这样的。

What it's showing in the output is the ASCII representation of the byte values.它在 output 中显示的是字节值的 ASCII 表示。 Hex 31 corresponds to the ascii character '1'.十六进制 31 对应于 ascii 字符“1”。 Try this to see a demonstration:试试这个看看演示:

bytes.fromhex('415343494921')

Here's a chart that shows these low values: https://en.wikipedia.org/wiki/ASCII#Control_code_chart这是显示这些低值的图表: https://en.wikipedia.org/wiki/ASCII#Control_code_chart

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM