2014-02-14 29 views
0

我想解压缩一些原始数据。 (它超过3个字节,但我已经减少到这个了。)python结构解压缩H或H对齐

我不希望在以下代码中回溯。我是不是该?由于对齐问题吗?正如你可以看到第二个成功。 (我的数据没有对齐,我可以编码,但是我需要吗?)

我期待(1,770)或(1,515)我想,不是例外。

http://docs.python.org/2/library/struct.html (B = UCHAR,1,8-和H =短,2,16)

Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win 
32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from struct import * 
>>> unpack('BH', '\x01\x02\x03') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    struct.error: unpack requires a string argument of length 4 
>>> unpack('HB', '\x01\x02\x03') 
(513, 3) 
>>> 
+0

嗨,什么是你真正想要解开? 123? – theAlse

+0

它的原始二进制数据如0x010203 ...(3个字节)来自一台机器,01是field1的值,0203是field2的值等等( Ignacio现在已经修复了它,它的工作非常好,谢谢。 ) – joec

回答

1

注:

  1. ...
  2. 没有填充被添加当使用非原生大小和对齐时,例如'<','>','='和'!'。

source

>>> struct.unpack('<BH', '\x01\x02\x03') 
(1, 770) 
>>> struct.unpack('>BH', '\x01\x02\x03') 
(1, 515) 
+0

优秀!谢谢。正是我想要的。 – joec