简体   繁体   English

在python中使用解包

[英]Using unpack in python

I have a list of data where in each member in the list contains a byte value.我有一个数据列表,其中列表中的每个成员都包含一个字节值。

list data = [0x00, 0x42, 0x00, 0xAD, 0x42, 010, 0xE0, 0xA2 ....]

This is the data that i receive from some external API.这是我从一些外部 API 收到的数据。 I need to map this data to fixed format.我需要将此数据映射到固定格式。

I am writing a class where in each field value can be retrieved .我正在编写一个类,可以在其中检索每个字段的值。

class FmtData
    def __init__(self, data):
        self.data = data

    def getParam1(self):
       //This a to return a value of 8 bytes starting from say index 1 in data

    def getParam2(self):
       // return 12 bits [20-31] corresponding bits from {byte 3 and 4 - 0x00 and 0xAD}

What is the best way to do it in python.在 python 中执行此操作的最佳方法是什么。

i am trying to use unpack from struct, but not sure how to extract specific bits ?我正在尝试从结构中解包,但不确定如何提取特定位?

First, you probably want to convert the list of bytes to bytearray(list_data) .首先,您可能希望将字节列表转换为bytearray(list_data)

However, the struct module doesn't handle sub-byte packing.但是, struct模块不处理子字节打包。 You could do it manually, but at that point, why even use struct ?您可以手动完成,但在那时,为什么还要使用struct


The ctypes module lets you define C-style structures, including bit fields. ctypes模块允许您定义 C 风格的结构,包括位域。 See Structures and unions in the docs.请参阅文档中的结构和联合 It's not as convenient for some use cases, but I think it will work for you here.对于某些用例来说,它不太方便,但我认为它在这里对您有用。 For example:例如:

from ctypes import *

class FmtStruct(Structure):
    _fields_ = [('padding', c_byte),
                #...
               ]

Then you construct a bytearray from the data, cast it to a FmtStruct , and just access the fields.然后你构建一个bytearray从数据来看, cast它一FmtStruct ,只是访问的字段。


You can also look at third-party modules which let you turn a string of bytes into a string of bits (without wasting 8x the storage), which you can then slice like any other string, and also let you turn any slice into an integer, which sounds like exactly what you want.您还可以查看第三方模块,这些模块可让您将一串字节转换为一串位(不会浪费 8 倍的存储空间),然后您可以像任何其他字符串一样对其进行切片,还可以将任何切片转换为整数,这听起来正是您想要的。 I don't have a specific module to recommend, but from a quick search, bitstring and bitarray look promising.我没有要推荐的特定模块,但从快速搜索来看, bitstringbitarray看起来很有希望。


Or, if speed and size aren't that important, just manually explode the list of bytes into a list of bits, slice it, and manually convert the slices to integers bit by bit (eg, via << and | ).或者,如果速度和大小不是那么重要,只需手动将字节列表分解为位列表,对其进行切片,然后手动将切片逐位转换为整数(例如,通过<<| )。

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

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