Skip to content

Instantly share code, notes, and snippets.

@vndee
Last active December 6, 2024 15:32
Show Gist options
  • Save vndee/63a4eee3dd20574a6b2c1df5e4bebe79 to your computer and use it in GitHub Desktop.
Save vndee/63a4eee3dd20574a6b2c1df5e4bebe79 to your computer and use it in GitHub Desktop.
def _read_length(self, f: BinaryIO) -> int:
"""Read a length-encoded integer"""
first_byte = f.read(1)[0]
# Check the first two bits (00, 01, 10, 11)
bits = first_byte >> 6
if bits == 0: # 00xxxxxx
return first_byte & 0x3F
elif bits == 1: # 01xxxxxx
next_byte = f.read(1)[0]
return ((first_byte & 0x3F) << 8) | next_byte
elif bits == 2: # 10xxxxxx
# Discard the remaining 6 bits and read a 32-bit integer
return struct.unpack(">I", f.read(4))[0]
else: # 11xxxxxx
remaining = first_byte & 0x3F
if remaining == 0: # Read 8 bit integer
return struct.unpack("B", f.read(1))[0]
elif remaining == 1: # Read 16 bit integer
return struct.unpack(">H", f.read(2))[0]
elif remaining == 2: # Read 32 bit integer
return struct.unpack(">I", f.read(4))[0]
else:
raise ValueError(f"Invalid length encoding: {first_byte}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment