Jump to content

[SOLVED] Convert to VarInt

Recommended Posts


Hello everybody!

I'm writing simple protocol for a server, I need to read/write VarInt, I'm not sure how to do it...

I'm going to send a string to server, but first, it need to send the length of string(StringLen) and convert it to VarInt and then send the string.


Name: VarInt         Size(bytes):  ≥ 1
≤ 5
      Encodes: An integer between -2147483648 and 2147483647       Notes:  Variable-length data encoding a two's complement signed 32-bit integer

More about VarInt:
Variable-length format such that smaller numbers use fewer bytes. These are very similar to Protocol Buffer Varints: the 7 least significant bits are used to encode the value and the most significant bit indicates whether there's another byte after it for the next part of the number. The least significant group is written first, followed by each of the more significant groups; thus, VarInts are effectively little endian (however, groups are 7 bits, not 8).

VarInts are never longer than 5 bytes.


//I found these examples, but I cannot understand them

public static int readVarInt() {
    int numRead = 0;
    int result = 0;
    byte read;
    do {
        read = readByte();
        int value = (read & 0b01111111);
        result |= (value << (7 * numRead));

        if (numRead > 5) {
            throw new RuntimeException("VarInt is too big");
    } while ((read & 0b10000000) != 0);

    return result;

public static void writeVarInt(int value) {
    do {
        byte temp = (byte)(value & 0b01111111);
        // Note: >>> means that the sign bit is shifted with the rest of the number rather than being left alone
        value >>>= 7;
        if (value != 0) {
            temp |= 0b10000000;
    } while (value != 0);

//It's written in Java

Sample VarInts:



Maybe somebody could tell me how it works that I would understand, or write an example in AutoIt language?


Edited by algiuxas


Share this post

Link to post
Share on other sites
Func pack_varint($val)
    $total = ""
    ;if $val < 0 Then $val =
    ConsoleWrite($val & @CRLF)
    while $val>=0x80
        $bits = BitAND($val,0x7F)
        $val = BitShift($val,7)
        $total &= Chr(BitOR(0x80,$bits))
    $bits = BitAND($val,0x7F)
    $total &= Chr($bits)
    return $total


How VarInt works: https://developers.google.com/protocol-buffers/docs/encoding#varints

VarInt phyton functions: https://gist.github.com/nickelpro/7312782


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now