sstevan
sstevan

Reputation: 487

Python: Converting HEX string to bytes

I'm trying to make byte frame which I will send via UDP. I have class Frame which has attributes sync, frameSize, data, checksum etc. I'm using hex strings for value representation. Like this:

testFrame = Frame("AA01","0034","44853600","D43F")

Now, I need to concatenate this hex values together and convert them to byte array like this?!

def convertToBits(self):
    stringMessage = self.sync + self.frameSize + self.data + self.chk
    return b16decode(self.stringMessage)

But when I print converted value I don't get the same values or I don't know to read python notation correctly:

This is sync: AA01
This is frame size: 0034
This is data:44853600
This is checksum: D43F

b'\xaa\x01\x004D\x856\x00\xd4?'

So, first word is converted ok (AA01 -> \xaa\x01) but (0034 -> \x004D) it's not the same. I tried to use bytearray.fromhex because I can use spaces between bytes but I got same result. Can you help me to send same hex words via UDP?

Upvotes: 1

Views: 14744

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122172

Python displays any byte that can represent a printable ASCII character as that character. 4 is the same as \x34, but as it opted to print the ASCII character in the representation.

So \x004 is really the same as \x00\x34, D\x856\x00 is the same as \x44\x85\x36\x00, and \xd4? is the same as \xd4\x3f, because:

>>> b'\x34'
'4'
>>> b'\x44'
'D'
>>> b'\x36'
'6'
>>> b'\x3f'
'?'

This is just the representation of the bytes value; the value is entirely correct and you don't need to do anything else.

If it helps, you can visualise the bytes values as hex again using binascii.hexlify():

>>> import binascii
>>> binascii.hexlify(b'\xaa\x01\x004D\x856\x00\xd4?')
b'aa01003444853600d43f'

and you'll see that 4, D, 6 and ? are once again represented by the correct hexadecimal characters.

Upvotes: 5

Related Questions