Skip to content

Instantly share code, notes, and snippets.

@eliemichel eliemichel/varint.py
Last active Mar 3, 2019

Embed
What would you like to do?
# 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
You can’t perform that action at this time.