6

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: ''
too honest for this site
12.3k4 gold badges33 silver badges53 bronze badges
asked Jul 23, 2017 at 20:09
7
  • Loop over the list and create a list converting all characters to integers? List comprehension would work well for that. Commented Jul 23, 2017 at 20:11
  • 1
    These outputs are absolutely the same. ord('2') == 50, ord('\x00') == 0, this is just a matter of representation. Commented Jul 23, 2017 at 20:12
  • @Someprogrammerdude see edit Commented Jul 23, 2017 at 20:14
  • If you'd printed the return value without list() you'd have noticed that the return value is '2\x002\x00' vs b'2\x002\x00'; and then you'd have asked about the difference between list('abc') in python 2 and list(b'abc') in Python 3. Commented Jul 23, 2017 at 20:17
  • @ForceBru they're not the same. One is a list of of str objects, the other is a list of int objects, obtained by iterating on a bytes object. Commented Jul 23, 2017 at 20:22

1 Answer 1

7

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)))
answered Jul 23, 2017 at 20:13
Sign up to request clarification or add additional context in comments.

1 Comment

I wish to be like you one day Sir!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.