Skip to content

Instantly share code, notes, and snippets.

@eliemichel
Last active March 3, 2019 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eliemichel/7c85738ae6d035fb7bcb7d976d3224a3 to your computer and use it in GitHub Desktop.
Save eliemichel/7c85738ae6d035fb7bcb7d976d3224a3 to your computer and use it in GitHub Desktop.
# Varint decoding: https://developers.google.com/protocol-buffers/docs/encoding
import struct
def readVarint(f):
multiplier = 1
value = 0
b = 0xff
while b & 128:
b = struct.unpack('B', f.read(1))[0]
value += multiplier * (b & 127)
multiplier *= 128
return value
def readSignedVarintArray(f, n):
buf = bytearray(n * 4)
for i in range(n):
value = readVarint(f)
value = value >> 1 ^ - (1 & value) # varint special sign managment
struct.pack_into("i", buf, i * 4, value)
return bytes(buf)
def readUnsignedVarintArray(f, n):
buf = bytearray(n * 4)
for i in range(n):
value = readVarint(f)
struct.pack_into("I", buf, i * 4, value)
return bytes(buf)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment