2

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?

prosseek
  • 182,215
  • 215
  • 566
  • 871
  • Would printing it out via `unpack` not provide what you want? What is your desired output? `4`? – sberry Jun 10 '13 at 19:39
  • 1
    If you want to reproduce what Python prints in your first example, use `print repr(val)`. – Aya Jun 10 '13 at 19:40

3 Answers3

1
>>> import struct
>>> print struct.unpack("i", struct.pack("i",4))[0]
4
jamylak
  • 128,818
  • 30
  • 231
  • 230
0

Based on: http://docs.python.org/2/library/struct.html

Python packs structures as byte strings, printing: print "%d" % int(val[0]) Will print the first character of the byte string (which is a character not an integer).

You are porobably look struct.unpack(fmt, string) from http://docs.python.org/2/library/struct.html.

i = pack("i",'\x04\x00\x00\x00')
print i
hazydev
  • 344
  • 1
  • 9
0

The issue was for hexadecimal value conversion, I had to use ord() method. int() method is only for a number in a string with base 10.

In [33]: int('4')
Out[33]: 4

In [34]: ord('\x34')
Out[34]: 52

In [35]: ord('4')
Out[35]: 52

In [36]: ord('\x10')
Out[36]: 16

So, this code works.

val = pack("i", 4)
print "%d" % ord(val[0]) # -> 4

or

print "%s" % hex(ord(val[0])) # -> 0x4
prosseek
  • 182,215
  • 215
  • 566
  • 871