hexpymodbusbitstring

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:

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.


Solution

  • What it's showing in the output is the ASCII representation of the byte values. Hex 31 corresponds to the ascii character '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