Meloun
Meloun

Reputation: 15059

Integer with ASCII values to string

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"

Upvotes: 1

Views: 893

Answers (2)

Scott Griffiths
Scott Griffiths

Reputation: 21925

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'

Upvotes: 1

Marco Mariani
Marco Mariani

Reputation: 13766

Not sure it's better, but :)

>>> import struct
>>> struct.pack('>L', 0x31323334)
'1234'

Upvotes: 1

Related Questions