Understanding struct.pack in python 2.7 and 3.5+

爱⌒轻易说出口 提交于 2020-05-13 05:35:40

问题


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: ''

回答1:


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)))


来源:https://stackoverflow.com/questions/45269456/understanding-struct-pack-in-python-2-7-and-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!