Read VarInt (variable integer) from DataStream
java/data/read-var-int
Variable-width integers, or varints, are at the core of the wire format. They allow encoding unsigned 64-bit integers using anywhere between one and ten bytes, with small values using fewer bytes. Each byte in the varint has a continuation bit that indicates if the byte that follows it is part of the varint.
1static void writeVarInt(DataOutputStream to, int toWrite) throws IOException {
2    while ((toWrite & -128) != 0) {
3        to.writeByte(toWrite & 127 | 128);
4        toWrite >>>= 7;
5    }
6    to.writeByte(toWrite);
7}
8
9static int readVarInt(DataInputStream input) throws IOException {
10    int i = 0;
11    int j = 0;
12    byte b0;
13
14    do {
15        b0 = input.readByte();
16        i |= (b0 & 127) << j++ * 7;
17    }
18    while ((b0 & 128) == 128);
19
20    return i;
21}
Unauthorized reproduction of original content on this website is prohibited.