Decode Hex String in Python 3

Decode Hex String in Python 3

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'

Just put the actual encoding you are using.

Convert from ASCII string encoded in Hex to plain ASCII?

A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

How do I actually decode a string to hex?

import base64

hex_str = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"

# Convert the hex string to bytes using the bytes' constructor
decoded = bytes.fromhex(hex_str)
assert decoded == b"I'm killing your brain like a poisonous mushroom"

# Convert the decoded bytes to base64 bytes using the base64 module
base64_bytes = base64.b64encode(decoded)
assert base64_bytes == b"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"

# Convert the base64 bytes to string using bytes method decode
base64_str = base64_bytes.decode('ascii')
assert base64_str == "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"

What's the correct way to convert bytes to a hex string in Python 3?

Since Python 3.5 this is finally no longer awkward:

>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'

and reverse:

>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'

works also with the mutable bytearray type.

Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex

Convert hex string to characters in python3

You just need to combine 2 steps: convert from hex to a bytestring with bytes.fromhex, and to print a bytestring to stdout using sys.stdout.buffer.write. Putting it all together:

import sys
sys.stdout.buffer.write(bytes.fromhex("5555555547aa")[::-1])

Sourced from hexadecimal string to byte array in python and How to write a raw hex byte to stdout in Python 3?



Related Topics



Leave a reply



Submit