Skip to content

Instantly share code, notes, and snippets.

@nickelpro
Created November 5, 2013 02:20
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickelpro/7312782 to your computer and use it in GitHub Desktop.
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.
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
@lachholden
Copy link

Super helpful, thanks! :)

@daill
Copy link

daill commented Jan 23, 2015

Thank you mate.

@jobl0ck
Copy link

jobl0ck commented Apr 22, 2022

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment