Adriaan Rol
Adriaan Rol

Reputation: 430

Python3 print in hex representation

I can find lot's of threads that tell me how to convert values to and from hex. I do not want to convert anything. Rather I want to print the bytes I already have in hex representation, e.g.

byteval = '\x60'.encode('ASCII')
print(byteval)  # b'\x60'

Instead when I do this I get:

byteval = '\x60'.encode('ASCII')
print(byteval)  # b'`' 

Because ` is the ASCII character that my byte corresponds to.

To clarify: type(byteval) is bytes, not string.

Upvotes: 4

Views: 15077

Answers (2)

justyy
justyy

Reputation: 6041

See this:

hexify = lambda s: [hex(ord(i)) for i in list(str(s))]

And

print(hexify("abcde"))
# ['0x61', '0x62', '0x63', '0x64', '0x65']

Another example:

byteval='\x60'.encode('ASCII')
hexify = lambda s: [hex(ord(i)) for i in list(str(s))]
print(hexify(byteval))
# ['0x62', '0x27', '0x60', '0x27']

Taken from https://helloacm.com/one-line-python-lambda-function-to-hexify-a-string-data-converting-ascii-code-to-hexadecimal/

Upvotes: 1

Robᵩ
Robᵩ

Reputation: 168626

>>> print("b'" + ''.join('\\x{:02x}'.format(x) for x in byteval) + "'")
b'\x60'

Upvotes: 5

Related Questions