
229 views
How to convert Hex to ASCII in python
To convert a hexadecimal string to ASCII in Python, you can use the built-in bytes.fromhex()
method, which takes a hexadecimal string as input and returns a bytes object. You can then decode the bytes to obtain the ASCII representation. Here’s an example:
Python
# Hexadecimal string
hex_string = "48656c6c6f2c20576f726c6421" # This represents "Hello, World!" in hex
# Convert hexadecimal string to bytes
hex_bytes = bytes.fromhex(hex_string)
# Decode the bytes to ASCII
ascii_text = hex_bytes.decode('ascii')
# Print the result
print(ascii_text)
In this example, bytes.fromhex(hex_string)
converts the hexadecimal string into a bytes object, and decode('ascii')
is used to decode the bytes object into an ASCII string.
The output of this code will be:
Plaintext
Hello, World!
This method is useful when you need to convert hexadecimal representations of data (e.g., binary data or encoded text) into human-readable ASCII text.