The hex() function can be used to convert a string to a hexadecimal value. Before using the function the value has to be converted to bytes.
1 2 |
s = 'hello'.encode('utf-8') print(s.hex()) |
The value is returned as a string representing a hexadecimal value.
68656c6c6f
Split these values into hex numbers:
0x68 0x65 0x6c 0x6c 0x6f
You can see, how are these values calculated.
Hex | Dec | Operation | ASCII |
0x68 | 104 | 6*16^1 + 8*16^0 = 6*16 + 8 * 1 = 104 | h |
0x65 | 101 | 6*16^1 + 5*16^0 = 6*16 + 5 * 1 = 101 | e |
0x6c | 108 | 6*16^1 + 12*16^0 = 6*16 + 12 * 1 = 108 | l |
0x6c | 108 | 6*16^1 + 12*16^0 = 6*16 + 12 * 1 = 108 | l |
0x6f | 111 | 6*16^1 + 15*16^0 = 6*16 + 15 * 1 = 111 | o |
Decode the value back to a string
If you want to decode this hex string into a string, you can use the following code, or read this tutorial.
1 |
print(bytes.fromhex('68656c6c6f').decode('utf-8')) |
This is the result:
hello