【问题标题】:What's the recommended "pythonic way" for unpacking a byte encoded message? [duplicate]解压字节编码消息的推荐“pythonic方式”是什么? [复制]
【发布时间】:2017-04-27 21:20:03
【问题描述】:

假设我有一个带有以下架构的字节打包消息:

Message Name: Ball
    Field #1: 
        Name: Color
        Type: unsigned int
        Start Bit: 0
        Bit Length: 4
    Field #2: 
        Name: Radius
        Type: single
        Start Bit: 4
        Bit Length: 32
    Field #3: 
        Name: New
        Type: bool
        Start Bit: 36
        Bit Length: 1

将字节序列转换为python变量的推荐pythonic方法是什么? “struct”模块能否很好地解压具有任意位长度字段的字节数组?

【问题讨论】:

  • 我怀疑这个问题最终会因某种原因而被关闭,但无论如何为了提供帮助,construct 可能比struct 更适合。
  • 嗯,看看this。
  • @juanpa.arrivillaga。我认为这是一个完美的例子。我非常熟悉如何在 C 中执行此操作,但我很好奇正确的 python 方法。我喜欢那篇文章中关于使用原生 python 库的参考资料。
  • @jwodder:谢谢。我会检查一下,但希望使用原生 python 方法。
  • @Pat 是的,如果你想做一些你会在 C 中做的事情,通常 ctypes 和 struct 可能需要查看 array 模块。跨度>

标签: python bytebuffer unpack


【解决方案1】:

推荐的将字节序列转换为python变量的pythonic方法是什么?

这个问题很快就会结束。你想要的是阅读this python doc page about struct and bytearrays。

它将向您展示如何使用格式来处理pack 和unpack 数据。

“struct”模块能否很好地解压具有任意位长度字段的字节数组?

它将向您展示如何使用格式来处理pack 和unpack 数据。

是的,如下:

import struct
color, radius, new = struct.unpack("If?", incoming_bytes)

检查format characters 以定义格式字符串,您就完成了。

您可以使用更多臃肿的库,例如construct,但TBH,这种格式非常简单,如果您早点unpack 和晚点pack,您可以在代码中随意组织数据。

例如:

class Ball:
    def __init__(self, color, radius, new):
        self.color = color
        self.radius = radius
        self.new = new

Ball(*unpack("If?", incoming_bytes))

【讨论】:

    猜你喜欢
    • 2011-01-15
    • 1970-01-01
    • 2012-11-29
    • 2011-01-02
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多