理解python 2.7和3.5+中的struct.pack [英] Understanding struct.pack in python 2.7 and 3.5+

查看:130
本文介绍了理解python 2.7和3.5+中的struct.pack的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解;并解决,为什么会发生以下情况:

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]

我知道 hh 代表 2 个短裤.我知道 struct.pack 正在将两个整数(shorts)转换为 c 风格的 struct.但是为什么 2.7 中的输出与 3.5 的差异如此之大?

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?

不幸的是,我现在在这个项目上坚持使用 python 2.7,我需要输出类似于 python 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: ''

推荐答案

在 python 2 中,struct.pack('hh', *(50,50)) 返回一个 str 对象.

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

这在python 3中发生了变化,它返回一个bytes对象(二进制和字符串之间的区别是两个版本之间非常重要的区别,即使bytes存在于python 2,它与 str 相同).

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

要在 python 2 中模拟这种行为,您可以通过将 ord 应用于结果的每个字符来获取字符的 ASCII 代码:

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

这篇关于理解python 2.7和3.5+中的struct.pack的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆