Created
November 5, 2013 02:20
-
-
Save nickelpro/7312782 to your computer and use it in GitHub Desktop.
Two python functions that implement the new Minecraft varint type (32-bit signed integers packed into Google protobuf varints). Packs varints into a byte string, unpacks varints from a buffer that has a read(bytes) method. Supports negative numbers even though they aren't used in the current protocol.
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
import struct | |
def pack_varint(val): | |
total = b'' | |
if val < 0: | |
val = (1<<32)+val | |
while val>=0x80: | |
bits = val&0x7F | |
val >>= 7 | |
total += struct.pack('B', (0x80|bits)) | |
bits = val&0x7F | |
total += struct.pack('B', bits) | |
return total | |
def unpack_varint(buff): | |
total = 0 | |
shift = 0 | |
val = 0x80 | |
while val&0x80: | |
val = struct.unpack('B', bbuff.read(1))[0] | |
total |= ((val&0x7F)<<shift) | |
shift += 7 | |
if total&(1<<31): | |
total = total - (1<<32) | |
return total |
Thank you mate.
Thanks
Thanks you very much!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Super helpful, thanks! :)