Print bytes as hex in Python

Print Bytes as Hex in Python

Bytes are encoded in ASCII and have a very dynamic role in Python. In Python 2, they were merely an alias to strings. However, Python 3 changed its definition as strings were now encoded as Unicode characters instead of ASCII encoded bytes.

Since bytes are ASCII encoded, the characters can be represented as integers between 0 to 255. We can represent them in other notations as well like systems with Hexadecimal digits.

In this article, we will discuss how to print Bytes as Hex in Python.

Using the hex() function to print Bytes as Hex in Python

Python 3.5 introduced the hex() function is used to return the Hexadecimal representation of a number. We can use it to directly print Bytes as Hex in Python.

First, we will create a Bytes array using the bytes() function and then we will print it as Hexadecimal digits. The output although, will not have any spaces in between the digits.

For example,

Output:

49162cd2

Note that this is the most efficient and fast method to achieve this representation.

Using the format() function to print Bytes as Hex in Python

The format() function can be used to represent the final output string in our desired style. We can specify the format specifiers within the function.

We can use this function to get the Hexadecimal representation of a number. For this, we will use the 02x specifier.

To print Bytes as Hex in Python, we will loop over a Byte string and get the Hexadecimal representation of each character individually. Then, we will join all the characters in a single string using the join() function.

We have implemented this logic in the following code.

Output:

49 16 2c d2

Using the binascii.hexlify() function to print Bytes as Hex in Python

The binascii module is a special module in Python that allows us to get various representations of binary and ASCII-coded bytes.

The hexlify() function works similarly to the hex() function discussed previously and provides us with the Hexadecimal representation of a byte.

See the code below.

Output:

b’49162cd2′

Note that the final output has the prefix b before the Hexadecimal representation. This means that it is of type bytes and not a string as in previous methods.

Conclusion

In this tutorial, we discussed how to print Bytes as Hex in Python. We first discussed bytes and their relation with integers and how it can be viewed as a collection of Hexadecimal digits.

In the first method, we use the hex() function. This is the fastest and most efficient method of all. Then we use string formatting using the format() attribute to get a hexadecimal representation of every character in the byte string and combine them. The final method involved the use of the hexlify() function which returns the result as bytes.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *