Printing out packing result from struct.pack

prosseek picture prosseek · Jun 10, 2013 · Viewed 9.6k times · Source

struct.pack returns packed result from input value.

In [19]: pack("i",4)
Out[19]: '\x04\x00\x00\x00'

I'm trying to printout the packed result as follows:

val = pack("i", 4)
print "%d" % int(val[0])

However, I got ValueError:

ValueError: invalid literal for int() with base 10: '\x04'

How can I print the packed value?

Answer

jamylak picture jamylak · Jun 10, 2013
>>> import struct
>>> print struct.unpack("i", struct.pack("i",4))[0]
4