Last active
March 3, 2019 16:01
-
-
Save eliemichel/7c85738ae6d035fb7bcb7d976d3224a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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