Read VarInt (variable integer) from DataStreamjava/data/read-var-intVariable-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}Disclaimer
The code snippet is provided for reference and learning purposes only. Users should use it at their own risk. I, along with the related developers, shall not be held responsible for any direct or indirect losses caused by the use of this code snippet, including but not limited to data loss, computer malfunctions, program errors, etc.