Skip to content

Instantly share code, notes, and snippets.

@SpaceManiac
Last active January 3, 2016 17:49
Show Gist options
  • Save SpaceManiac/8498132 to your computer and use it in GitHub Desktop.
Save SpaceManiac/8498132 to your computer and use it in GitHub Desktop.
VarInt reading/writing from Glowstone
/**
* The bit flag indicating a varint continues.
*/
public static final byte VARINT_MORE_FLAG = (byte) (1 << 7);
/**
* Read a protobuf varint from the buffer.
* @param buf The buffer.
* @return The value read.
*/
public static int readVarInt(ChannelBuffer buf) {
int ret = 0;
short read;
byte offset = 0;
do {
read = buf.readUnsignedByte();
ret = ret | ((read & ~VARINT_MORE_FLAG) << offset);
offset += 7;
} while (((read >> 7) & 1) != 0);
return ret;
}
/**
* Write a protobuf varint to the buffer.
* @param buf The buffer.
* @param num The value to write.
*/
public static void writeVarInt(ChannelBuffer buf, int num) {
do {
short write = (short) (num & ~VARINT_MORE_FLAG);
num >>= 7;
if (num != 0) {
write |= VARINT_MORE_FLAG;
}
buf.writeByte(write);
} while (num != 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment