繁体   English   中英

python解压缩二进制数据

[英]python unpack binary data

我正在为半径编写rlm_python模块,该模块从“ Accouting-Request”数据包中获取位置

但是,该位置采用二进制格式,

 "\001\027\002\025\001+\001\024"

当我尝试使用struct拆包时

[root@server ~]# python 
Python 2.4.3 (#1, May  5 2011, 16:39:10) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from struct import *
>>> unpack('hhl',"\001\027\002\025\001+\001\024" )
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format

任何想法,我怎么能解包这些数据?

您的字符串长度为8个字节,但是unpack可能不会这样(除非您使用修饰符,否则大小取决于平台)。

Python 2.4.3 (#1, May  5 2011, 16:39:10) 
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from struct import *
>>> unpack('hhl',"\001\027\002\025\001+\001\024" )
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
struct.error: unpack str size does not match format
>>> unpack('=hhl',"\001\027\002\025\001+\001\024" )
(5889, 5378, 335620865)

struct.unpack docs

如果第一个字符不是其中一个,则假定为“ @”。 使用C编译器的sizeof表达式确定本机大小和对齐方式。 这始终与本机字节顺序结合在一起。 标准尺寸仅取决于格式字符; 请参阅“格式字符”部分中的表。

>>> import struct
>>> data = "\001\027\002\025\001+\001\024"
>>> data
'\x01\x17\x02\x15\x01+\x01\x14'
>>> len(data)
8
>>> struct.calcsize('hhl')
16
>>> struct.calcsize('!hhl')
8
>>> struct.unpack('!hhl',data)
(279, 533, 19595540)

除非您修改构造函数,否则某些元素的大小可能会更改,具体取决于您的体系结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM