Startec
Startec

Reputation: 13206

Show hex value for all bytes, even when ASCII characters are present

In Python (3) at least, if a binary value has an ASCII representation, it is shown instead of the hexadecimal value. For instance, the binary value of 67 which is ASCII C is show as follows:

bytes([67]) # b'C'

Whereas for binary values without ASCII representations, they are shown in hex. I.E.

b'\x0f'

Is there a way to force Python to show the binary values in their binary-hex form (if this is what it is called), even when there are ASCII representations?

Edit: By this I mean, something that starts with b'\x',. This would make debugging easier when you are looking for specific bytes to be printed for instance.

Thanks

Upvotes: 21

Views: 11644

Answers (2)

wim
wim

Reputation: 363063

After installing my package all-escapes there will be a new codec available for this usage.

>>> b = bytes([10,67,128])
>>> print(b.decode("all-escapes"))
\x0a\x43\x80

Upvotes: 6

BrenBarn
BrenBarn

Reputation: 251428

There is no specific means of requiring any particular formatting (like \x) for a byte string. If you really need specific formatting, you could use something like the .hex() solution from this question, but wrap it with other code to insert the formatting you need. Another useful tool is the hex builtin function. For instance, if you want \x:

>>> x = bytes([67, 128])
>>> print(''.join(r'\x'+hex(letter)[2:] for letter in x))
\x43\x80

If you just need to be able to visually distinguish the bytes, using hex by itself may work for you (it uses 0x instead of \x):

>>> print(''.join(hex(letter) for letter in x))
0x430x80

There is not a way to make this the default behavior for byte strings. Whatever you do, you're going to have to write code that specifies the display format you want; you can't make Python automatically display printable bytes as \x escapes.

Upvotes: 3

Related Questions