'Converting an integer to a string of escaped hex (NOT bytes)
I am trying to come up with a way to convert an integer to a string of escaped hex, as if it was coded that way... for example:
x = '\xab\xcd\xff\xff'
I have tried the following function, but it appears that chr() only does this for characters with the integer value 160 and below:
def int2chr(val, size):
out = ''
for _ in range(size):
tmp = val & 0xff
val >>= 8
out = f'{chr(tmp)}{out}'
return out`
From this, I get:
>>> int2chr(0xabcdffff, 4)
'����'
>>>
I would like it to return '\xab\xcd\xff\xff' instead...
This doesn't work any better:
def int2chr(val, size):
out = ''
for _ in range(size):
tmp = val & 0xff
val >>= 8
out = f'\\x{hex(tmp)[2:]}{out}'
return out
>>> int2chr(0xabcdffff,4)
'\\xab\\xcd\\xff\\xff'
>>>
The closest I've been able to come gives me bytes, not a string:
b'\xab\xcd\xff\xff'
I am very surprised that there isn't an easy way to do this. Can anyone shed some light?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
