struct pack 问题,与文档上的结果不一样

2014-12-20 13:22:28 +08:00
 sbmzhcn
文档上的例子:
A basic example of packing/unpacking three integers:

>>>
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
>>> calcsize('hhl')
8

我电脑上的实际结果:
Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from struct import *
>>> pack('hhl', 1, 2, 3)
'\x01\x00\x02\x00\x03\x00\x00\x00'
>>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(256, 512, 50331648)
>>> calcsize('hhl')
8
>>>
2434 次点击
所在节点    Python
6 条回复
casparchen
2014-12-20 13:35:24 +08:00
是我眼睛看花了吗, 你pack的结果跟unpack时用的不一致
savebox
2014-12-20 13:40:03 +08:00
bigendian和little endian的问题
你os是win 例子里面就不一定是win哦
sbmzhcn
2014-12-20 13:40:18 +08:00
@casparchen 是不一样,你没看到上面的代码有问题吗, 1 pack的结果应该是 \x00\x01 但实际却是\x01\x00,

原文档: unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') 结果是(1, 2, 3)
我的unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') 结果是(256, 512, 50331648)
sbmzhcn
2014-12-20 13:41:27 +08:00
@savebox 怎么解决,我现在需要 pack('h', 16) 的结果是 \x00\x10 但它的结果总是 \x10\x00
glasslion
2014-12-20 13:45:54 +08:00
http://zh.wikipedia.org/wiki/%E5%AD%97%E8%8A%82%E5%BA%8F

By default, C types are represented in the machine’s native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler).

pack('>hhl', 1, 2, 3)
Out[8]: '\x00\x01\x00\x02\x00\x00\x00\x03'

pack('<hhl', 1, 2, 3)
Out[9]: '\x01\x00\x02\x00\x03\x00\x00\x00'

unpack('>hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
Out[10]: (1, 2, 3)

unpack('<hhl', '\x01\x00\x02\x00\x03\x00\x00\x00')
Out[11]: (1, 2, 3)
savebox
2014-12-20 13:47:52 +08:00
>>> unpack('<hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(256, 512, 50331648)
>>> unpack('>hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)

我都是强制加上>或<, 看手册,>是big.<是little, 不加就是系统默认的endian格式,pack同样

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/155300

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX