0

I am working with binary data that is stored in a byte array and I need to access bits of arbitrary length inside this array. Performance is also a concern. Let me give a brief example:

# 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

My above solution works, but a typical byte array has 20 bytes and therefore the code gets unreadable and is definitely not intuitive at a first glance.

Modules like struct won't help, because they ONLY can unpack bytes, e.g. 2^X

sjakobi
  • 3,546
  • 1
  • 25
  • 43
Leonleon1
  • 165
  • 2
  • 8

0 Answers0