1

I have an integer containing four ASCII codes for four chars:

0x31323334

I need to convert this integer to a string:

"1234" ~ "\x31\x32\x33\x34"

Is there better solution than this?

mystring = '%0*x' % (8, 0x31323334) # "31323334"
mystring.decode('hex') # "1234"
6
  • I think your way is OK. I would use instead str('0x31323334')[2:].decode('hex') as I think it's more readable, but the basic idea is the same. Commented Jan 2, 2012 at 21:27
  • @Eduardo Perhaps you mean hex(0x31323334)[2:].decode('hex')? Commented Jan 2, 2012 at 22:00
  • @Dunes: that's better! I did mean the sloppier version : ) Commented Jan 2, 2012 at 22:12
  • 1
    @Dunes: Almost - works for this case, but not in general. If the number starts with zeros then it either loses characters of fails with a TypeError. Commented Jan 2, 2012 at 23:21
  • @Scott Issue with zeroes is very important for me, I have to consider that. Commented Jan 3, 2012 at 8:41

2 Answers 2

1

Not sure it's better, but :)

>>> import struct
>>> struct.pack('>L', 0x31323334)
'1234'
Sign up to request clarification or add additional context in comments.

5 Comments

In Python 2.6 / 2.7 I get '\x00\x00\x00\x001234'. Works for Python 2.5 though.
64 bit, I suppose... never used that package. can you try as I edited, with struct.pack('>L', 0x31323334)? it should be big-endian, 4 bytes wide.
Yes it's a 32 vs. 64 bit thing, nothing to do with the Python version - my misunderstanding. It makes no difference with the 'L' format, on 64 bit struct.calcsize('L') is 8.
Using '>I' will be more portable. Most 64-bit systems have 64-bit longs, the only exception is Windows.
@DietrichEpp: I don't think there's a difference between '>L' and '>I' - according to the docs (and my tests) they are both the 'standard' 4 bytes long. It's only different if you use the native size, which might be 8 for a 'L' on non-Windows 64-bit Python.
1

I don't think you'll get simpler than a format string and then a decode (needs Python 2.6+):

>>> "{0:08x}".format(0x31323334).decode('hex')
'1234'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.