簡體   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