Force python to display hex as hex

Viewed 29

I have a program which makes binary substitutions to a file. As part of this program a regular expression match object is created to match the binary to be substituted. This is in the form:

a = re.compile(b"|".join([list_of_hex_to_be_substituted])

This object is then printed for debugging purposes. However, when it is printed I encounter the issue that python substitutes some hex values for their ascii equivalents and leaves some alone. In an extreme example this can result in issues like

print(b"\x01\x00\x5C\x78\x33\x34")
--> b"\x01\x00\\x34

as 5C 78 33 34 in ascii is \x34. This is extremely confusing when debugging the script. What I am looking for is a way to simply print the hex as hex (no ascii substiution)

1 Answers

Answer

There is the bytes.hex method for that:

 hex([sep[, bytes_per_sep]])

Return a string object containing two hexadecimal digits for each byte in the instance.

If you want to make the hex string easier to read, you can specify a single character separator sep parameter to include in the output. By default, this separator will be included between each byte. A second optional bytes_per_sep parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.

NOTE: The optional parameters are present since version 3.8 and the method is introduced in version 3.5

Examples

  1. Without parameters

Here is some examples without parameters, notice that the default value for sep is an empty string(e.g. '', "")

>>> b'\xf0\xf1\xf2'.hex()
'f0f1f2'
  1. using the sep and the bytes_per_sep parameters

Here are some examples using both optional parameters if you have any doubt on how these work, they should be clear with this example:

>>> value = b"\x01\x00\x5C\x78\x33\x34"
>>> value.hex(' ',1)
'01 00 5c 78 33 34'
>>> value.hex(" ",2)
'0100 5c78 3334'
Related