Jim
Jim

Reputation: 373

Why does bytes.fromhex() treat some hex values strangely?

I'm trying to use the socket library in Python to send bytes of two hex digits to a piece of hardware programmed to accept them. To create the bytes from a user-entered string of hex digits, I'm trying to use bytes.fromhex() method described here.

Why does the following:

hexstring = "bb 0D 02 55 55 5A ce"
data = bytes.fromhex(hexstring)
print(data)

give me:

b'\xbb\r\x02UUZ\xce'

instead of:

b'\xbb\x0d\x02\x55\x55\x5a\xce'

?

And how do I get it to produce the second output? I'm using Python 3.5.

Upvotes: 8

Views: 23289

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122382

This has nothing to do with bytes.fromhex(). You'd get the same result if you entered your expected result into Python:

>>> b'\xbb\x0d\x02\x55\x55\x5a\xce'
b'\xbb\r\x02UUZ\xce'

The repr() representation of a bytes object will always use ASCII printable characters and short one-letter escape sequences where possible.

So \x0d is displayed as \r, because that's the ASCII code point for a carriage return. \x55 is the printable ASCII character U, etc.

If this is an issue for you, you'll have to explicitly convert your bytes value to hexadecimal again:

>>> b'\xbb\r\x02UUZ\xce'.hex()
'bb0d0255555ace'

Upvotes: 13

user3030010
user3030010

Reputation: 1857

Python automatically displays bytes that can be interpreted as printable ASCII as the characters they print. For example, chr(0x55) == 'U', so Python just prints U instead of the hexcode. It is still the same data.

Upvotes: 2

Related Questions