我正在尝试理解和解决为什么会发生以下情况:
$ 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]
我知道hh
代表2个短裤。我知道struct.pack
正在将两个整数(短整型)转换为c style struct
。但为什么2.7中的输出与3.5中的输出有如此大的差异?
不幸的是,我现在在这个项目上被python 2.7
卡住了,我需要输出类似于python 3.5
的输出
作为对来自某个程序员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: ''
发布于 2017-07-23 20:13:56
在Python2中,struct.pack('hh', *(50,50))
返回一个str
对象。
这在Python3中发生了变化,它返回一个bytes
对象(二进制和字符串之间的区别是两个版本之间的一个非常重要的区别,即使在Python2中存在bytes
,它也与str
相同)。
为了在Python2中模拟这种行为,您可以通过将ord
应用于结果的每个字符来获得字符的ASCII码:
map(ord,struct.pack('hh', *(50,50)))
https://stackoverflow.com/questions/45269456
复制相似问题