Java ByteBuffer Read readVInt(ByteBuffer bb)

Here you can find the source of readVInt(ByteBuffer bb)

Description

Reads an int stored in variable-length format.

License

Apache License

Parameter

Parameter Description
bb bb

Return

int int

Declaration

public static int readVInt(ByteBuffer bb) 

Method Source Code

//package com.java2s;
/**/*from  w w  w . j  ava 2  s. com*/
 * Copyright 2004 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.nio.ByteBuffer;

public class Main {
    /** Reads an int stored in variable-length format.  Reads between one and
     * five bytes.  Smaller values take fewer bytes.  Negative numbers are not
     * supported.
     * @param bb bb
     * @return int int
     */
    public static int readVInt(ByteBuffer bb) {
        /* This is the original code of this method,
         * but a Hotspot bug (see LUCENE-2975) corrupts the for-loop if
         * readByte() is inlined. So the loop was unwinded!
        byte b = readByte();
        int i = b & 0x7F;
        for (int shift = 7; (b & 0x80) != 0; shift += 7) {
          b = readByte();
          i |= (b & 0x7F) << shift;
        }
        return i;
         */
        byte b = bb.get();
        int i = b & 0x7F;
        if ((b & 0x80) == 0)
            return i;
        b = bb.get();
        i |= (b & 0x7F) << 7;
        if ((b & 0x80) == 0)
            return i;
        b = bb.get();
        i |= (b & 0x7F) << 14;
        if ((b & 0x80) == 0)
            return i;
        b = bb.get();
        i |= (b & 0x7F) << 21;
        if ((b & 0x80) == 0)
            return i;
        b = bb.get();
        assert (b & 0x80) == 0;
        return i | ((b & 0x7F) << 28);
    }
}

Related

  1. readTs(ByteBuffer is)
  2. readTs(ByteBuffer is, int c)
  3. readUUID(ByteBuffer buffer)
  4. readVariableLength(ByteBuffer buf)
  5. readVInt(ByteBuffer bb)
  6. readVL(ByteBuffer byteBuffer)
  7. readZeroTermStr(ByteBuffer bb)