1

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?

3
  • 3
    have you tried anything? Commented Apr 10, 2013 at 19:06
  • 1
    Dang, my copy/paste buffer missed. I meant to mark this one: stackoverflow.com/questions/1708598/… Commented Apr 10, 2013 at 19:10
  • I tried hex(integer)[2:].zfill(8). But this only returns a hex without the "\x". Commented Apr 10, 2013 at 19:15

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

10 Comments

LOL I should start copying answers instead of marking as duplicates from now on. stackoverflow.com/questions/1708598/…
I'm not sure why this was downvoted. Sure, it shouldn't be upvoted, because it was posted after the "possible duplicate" link to the exact same answer, and the question should be closed anyway… but it's not wrong, misleading, confusing, etc., so why downvote it?
struct.pack('>i", 67) returns "C". I need it to return "\x00\x00\x00\x43"
Oops. I didn't notice you'd marked this as a dupe before I posted the answer. If you're going to mark as a dupe, should you not also close the question at the same time to avoid confusion?
@abarnert I downvoted because it was wrong and doesn't answer the OP's question.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.