Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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

like image 404
Startec Avatar asked Oct 25 '14 23:10

Startec


People also ask

Does ASCII use hexadecimal?

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.

What is ASCII hex code?

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.

How many bytes is an ASCII character?

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).


1 Answers

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.

like image 120
BrenBarn Avatar answered Sep 17 '22 19:09

BrenBarn