I have a binary string formatted like so:
- (short) num_tables
- (short) table_width
- (short) table_height
- Tables:
- (3 * width * height * short) table_data
- ... repeated
num_tables
times
Currently I'm parsing this out with this really ugly mess:
def decode_table_data(input_bytes):
# Data is little-endian
num_tables = input_bytes[0] + (input_bytes[1] << 8)
table_width = input_bytes[2] + (input_bytes[3] << 8)
table_height = input_bytes[4] + (input_bytes[5] << 8)
# TODO: Extract table_data
This is obviously hard to read, ugly, takes a while to type out, and prone to errors. I would prefer a syntax like:
def decode_table_data(input_bytes):
num_tables = input_bytes.read_short(little_endian=True)
table_width = input_bytes.read_short(little_endian=True)
table_height = input_bytes.read_short(little_endian=True)
I know many languages have tools for reading byte arrays like this (read_short
, read_int
, etc). Is there such a tool in Python? I tried Googling around for it but couldn't find anything easily.