Question

I have an integer (67) that needs to be converted to hex and stored as a string like:

"\x00\x00\x00\x43"

How can I do this in Python?

Was it helpful?

Solution

Updated due to ambiguity in OP.

Try...

def convert(i):
    result = ''
    for c in struct.pack('>i', 67):
        c = hex(ord(c))[2:]
        if len(c) < 2:
            c = '0%s' % c
        result += '\\x%s' % c
    return result

>>> print convert(67)
\x00\x00\x00\x43
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top