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
ASCII Code (Hexadecimal) The ASCII characters are numbered from 00 to FF in hexadecimal. Note that 0 to 9 are the same in both numbering systems. To understand hex numbers, see hex.
ASCII stands for American Standard Code for Information Interchange. It ranges from 0 to 255 in Decimal or 00 to FF in Hexadecimal. ASCII codes can be divided into two sets - Standard ASCII codes and Extended ASCII codes.
An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits. An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With