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:
Code:
def hex_str_to_bytes(hex_string):
try:
bytes_sequence = bytes.fromhex(hex_string)
return bytes_sequence
except ValueError as ve:
print("Error:", ve)
return None
def main():
try:
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__":
main()
Output:
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/extended-data-types/python-extended-data-types-bytes-bytearrays-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics