【问题标题】:How to use python struct package to only unpack first 6 bytes如何使用 python struct 包仅解包前 6 个字节
【发布时间】:2021-11-28 08:39:30
【问题描述】:

我想使用 struct 包只为我提供一些有效负载的前 6 个字节,因为我并不总是知道大小,例如

b'A\x10VuGe\x00d\x0c\xf4\x06\x0cf\x00'

如果我知道缓冲区的大小,以下代码可以工作:

import struct
from datetime import datetime
from pytz import UTC
import json
from django.utils.encoding import smart_str

data2 = b'A\x10VuGe\x00d\x0c\xf4\x06\x0cf\x00'
devid,hw,sw,bat,ss,distance,interrupt  = struct.unpack('>6sBBHbHb',data2)

print(f"DeviceID={devid.hex()} HW={hw} SW={'.'.join(str(sw))} "
      f"BAT={bat:.3f}mV SignalStrength={-113+2*ss}dBm "
      f"Distance={distance} "
      f"Interrupt={interrupt}")

【问题讨论】:

  • 您可以对字符串中已知的字节应用相同的切片表示法。
  • 我不明白,你能解释一下吗?

标签: python struct hex


【解决方案1】:

只需使用:data = data[0:14],您将拥有前 14 个字节。 不如按照你的方式解包

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 2019-03-31
    • 2020-01-28
    • 2017-12-26
    • 2020-03-03
    相关资源
    最近更新 更多