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?

emecas
  • 1,586
  • 3
  • 27
  • 43

1 Answers1

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
Aya
  • 39,884
  • 6
  • 55
  • 55
  • LOL I should start copying answers instead of marking as duplicates from now on. http://stackoverflow.com/questions/1708598/convert-decimal-to-hex-python?rq=1 – 000 Apr 10 '13 at 19:15
  • 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? – abarnert Apr 10 '13 at 19:17
  • struct.pack('>i", 67) returns "C". I need it to return "\x00\x00\x00\x43" – user2267580 Apr 10 '13 at 19:19
  • 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? – Aya Apr 10 '13 at 19:20
  • @abarnert I downvoted because it was wrong and doesn't answer the OP's question. – Asad Saeeduddin Apr 10 '13 at 19:20
  • @Aya Marking as duplicate is a recent wording change to closing as duplicate. They are equivalent. – Asad Saeeduddin Apr 10 '13 at 19:21
  • @user2267580 struct.pack('>i", 67) returns '\x00\x00\x00C' which is the same as "\x00\x00\x00\x43", unless you actually wanted a string containing the backslashes? – Aya Apr 10 '13 at 19:23
  • Yes, I want the actual string "\x00\x00\x00\x43" returned. – user2267580 Apr 10 '13 at 19:29
  • Updated. There's probably a better method, but I only answered this because I originally thought it was a one-liner. Had I known I would be chastised for my troubles, I probably wouldn't have bothered. :/ – Aya Apr 10 '13 at 19:50
  • Downvote is now an upvote :) – 000 Apr 10 '13 at 23:08