Java ByteBuffer to Int readVarInt(ByteBuffer buff)

Here you can find the source of readVarInt(ByteBuffer buff)

Description

Read a variable size int.

License

Mozilla Public License

Parameter

Parameter Description
buff the source buffer

Return

the value

Declaration

public static int readVarInt(ByteBuffer buff) 

Method Source Code

//package com.java2s;
/*//from   w w w. ja  v a2 s  .  com
 * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
 * and the EPL 1.0 (http://h2database.com/html/license.html).
 * Initial Developer: H2 Group
 */

import java.nio.ByteBuffer;

public class Main {
    /**
     * Read a variable size int.
     *
     * @param buff the source buffer
     * @return the value
     */
    public static int readVarInt(ByteBuffer buff) {
        int b = buff.get();
        if (b >= 0) {
            return b;
        }
        // a separate function so that this one can be inlined
        return readVarIntRest(buff, b);
    }

    private static int readVarIntRest(ByteBuffer buff, int b) {
        int x = b & 0x7f;
        b = buff.get();
        if (b >= 0) {
            return x | (b << 7);
        }
        x |= (b & 0x7f) << 7;
        b = buff.get();
        if (b >= 0) {
            return x | (b << 14);
        }
        x |= (b & 0x7f) << 14;
        b = buff.get();
        if (b >= 0) {
            return x | b << 21;
        }
        x |= ((b & 0x7f) << 21) | (buff.get() << 28);
        return x;
    }
}

Related

  1. readUnsignedMedium(ByteBuffer buf)
  2. readUnsignedShort(ByteBuffer bb)
  3. readUnsignedShort(ByteBuffer buffer)
  4. readUnsignedTriByte(ByteBuffer buffer)
  5. readUnsignedVarint(ByteBuffer buffer)
  6. readVarInt(ByteBuffer buff)
  7. readVarint(ByteBuffer buffer)
  8. readVarInt(ByteBuffer buffer)
  9. readVarInt(ByteBuffer stream)