Python Program: Convert hexadecimal string to bytes

Python Bytes and Byte Arrays Data Type: Exercise-5 with Solution

Write a Python program that converts a hexadecimal string into a bytes sequence.

Sample Solution:


def hex_str_to_bytes(hex_string):
        bytes_sequence = bytes.fromhex(hex_string)
        return bytes_sequence
    except ValueError as ve:
        print("Error:", ve)
        return None

def main():
        hex_string = "4861636b657220436f6465" 
        bytes_result = hex_str_to_bytes(hex_string)
        if bytes_result is not None:
            print("Hexadecimal String:", hex_string)
            print("Bytes Sequence:", bytes_result)
            print("Decoded String:", bytes_result.decode("utf-8"))
    except Exception as e:
        print("An error occurred:", e)

if __name__ == "__main__":


Hexadecimal String: 4861636b657220436f6465
Bytes Sequence: b'Hacker Code'
Decoded String: Hacker Code

In the exercise above, the "hex_string_to_bytes()" function takes a hexadecimal string as input and converts it into a bytes sequence using the "bytes.fromhex()" method. In the "main()" function, a sample hexadecimal string is provided and the resultant bytes sequence and decoded string are printed.


Flowchart: Python Program: Convert hexadecimal string to bytes.

Previous: Read and modify image as bytes.
Next: Python Function: Reverse a given bytes object.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.