python - 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
解决方案
推荐阅读
- java - ByteBufferBackedInputStream 重新填充 ByteBuffer
- adobe-indesign - How to show and hide standard InDesign panels through scripting?
- powershell - 在 PowerShell 中调用静态类方法
- rust - 比较 Rust 中的字符串长度
- entity-framework - 使用 asp.net core 和 EF core 构建可定制的报告生成向导
- selenium - Jenkins 在 Firefox 上的无头测试执行
- python - 如何从 HFS 分割图像中提取轮廓
- python - 我如何轻松找到一个数字是否是 2 的幂?
- c# - 在 VS Code 中将函数名称(函数头)变为粗体
- python - 在 jupyter notebook 中使用 opencv 时出错: