Skip to main content

Python examples for converting bytes to hex and hex to bytes.

#!/usr/bin/env python3

def convert_plain_text_string_to_hex_text_string():
    import binascii

    plain_text = 'Hello world!'

    # Create an encoded version plain_text string as a bytes object:
    encoded_bytes = plain_text.encode('utf-8')

    # Create a hexadecimal representation of the encoded_bytes, and convert it to a text string:
    hexadecimal_text = binascii.hexlify(encoded_bytes).decode('utf-8')
    # Similar functionality is available using the `bytes.hex()` method:
    #hexadecimal_text = bytes.hex(encoded_bytes)


def convert_hex_text_string_to_plain_text_string():
    hexadecimal_text = '48656c6c6f20776f726c6421'

    # Create an encoded bytes object from the hexadecimal_text string:
    encoded_bytes = bytes.fromhex(hexadecimal_text)

    # Create a plain text representation of the encoded_bytes:
    plain_text = encoded_bytes.decode('utf-8')


convert_plain_text_string_to_hex_text_string()  # 48656c6c6f20776f726c6421
convert_hex_text_string_to_plain_text_string()  # Hello world!

# Hat tip: