Skip to content

Instantly share code, notes, and snippets.

@nickelpro
Created November 5, 2013 02:20
Show Gist options
  • Select an option

  • Save nickelpro/7312782 to your computer and use it in GitHub Desktop.

Select an option

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
@lachsh
Copy link
Copy Markdown

lachsh commented Dec 1, 2013

Super helpful, thanks! :)

@daill
Copy link
Copy Markdown

daill commented Jan 23, 2015

Thank you mate.

@jobl0ck
Copy link
Copy Markdown

jobl0ck commented Apr 22, 2022

Thanks

@BoBkiNN
Copy link
Copy Markdown

BoBkiNN commented May 18, 2024

Thanks you very much!!!

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