4

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.

Adriaan Rol
  • 420
  • 2
  • 4
  • 12

2 Answers2

5
>>> print("b'" + ''.join('\\x{:02x}'.format(x) for x in byteval) + "'")
b'\x60'
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

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/

justyy
  • 5,831
  • 4
  • 40
  • 73