Sam Hammamy
Sam Hammamy

Reputation: 11017

Understanding struct.pack in python 2.7 and 3.5+

I am attempting to understand; and resolve, why the following happens:

$ python
>>> import struct
>>> list(struct.pack('hh', *(50,50)))
['2', '\x00', '2', '\x00']
>>> exit()
$ python3
>>> import struct
>>> list(struct.pack('hh', *(50, 50)))
[50, 0, 50, 0]

I understand that hh stands for 2 shorts. I understand that struct.pack is converting the two integers (shorts) to a c style struct. But why does the output in 2.7 differ so much from 3.5?

Unfortunately I am stuck with python 2.7 for right now on this project and I need the output to be similar to one from python 3.5

In response to comment from Some Programmer Dude

$ python
>>> import struct
>>> a = list(struct.pack('hh', *(50, 50)))
>>> [int(_) for _ in a]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

Upvotes: 6

Views: 7328

Answers (1)

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140307

in python 2, struct.pack('hh', *(50,50)) returns a str object.

This has changed in python 3, where it returns a bytes object (difference between binary and string is a very important difference between both versions, even if bytes exists in python 2, it is the same as str).

To emulate this behaviour in python 2, you could get ASCII code of the characters by appling ord to each char of the result:

map(ord,struct.pack('hh', *(50,50)))

Upvotes: 7

Related Questions