首页 > 解决方案 > Python - 处理不是 2 倍数的二进制数据的优雅方式

问题描述

我正在处理存储在字节数组中的二进制数据,我需要访问该数组中任意长度的位。性能也是一个问题。让我举一个简单的例子:

# 11111111 | 11101111 | 01111100
byte_arr = bytearray([255, 239, 124])

# A corresponds to the first 6 bits, e.g. index 0-5
a = byte_arr[0]>>2 

# B corresponds to the next 2 bits, e.g. index 6-7
b = byte_arr[0] & 0x3

# C corresponds to the next 9 bits, e.g. index 8-16
c = int.from_bytes(byte_arr[1::], byteorder="big", signed=False)>>7

我上面的解决方案有效,但是一个典型的字节数组有 20 个字节,因此代码变得不可读,乍一看肯定不直观。

struct 之类的模块无济于事,因为它们只能解包字节,例如 2^X

标签: pythonarraysbit-manipulationbyte

解决方案


推荐阅读