I am trying to convert an int to hex in string. The current solutions do not work as intended.
The hex must be in \x format. E.g. 255 -> \xff; 65 -> \x41
Accepted Solution from a similar question
chr(1) # '\x01'; This is okay.
chr(65) # 'A'
chr(255) # 'ΓΏ'
The output is nothing like hex even if they equal to their corresponding hex values. The output has to be a \x formatted hex.
Using hex()
hex(1) # '0x1'
hex(65) # '0x41'
hex(255) # '0xff'
No luck here. x is followed by 0 so it is not useful. hex(1) does not have a 0 before the 1. I would like to have that. Better yet, a padding length of my choice.
repr(chr(65)) as suggested in the comments does not work either.
hex() with replacement
chr(255).replace('0', "\\") # '\\xff'
hex(255).replace('0x', "\\x") # '\\xff'
Cannot use replace() either cause \ has to be escaped or the code does not even work. I really would like to avoid a solution that requires modifying a string since copying is involved.
int.to_bytes
int.to_bytes(1, 1, 'big') # b'\x01'
int.to_bytes(65, 1, 'big') # b'A'; Why is this suddenly 'A'? Why not b'\x41'
int.to_bytes(255, 1, 'big') # b'\xff'
A pythonic, performant solution to the problem is greatly appreciated.