Java ByteBuffer Read readSignedVarint(ByteBuffer buffer)

Here you can find the source of readSignedVarint(ByteBuffer buffer)

Description

Read a signed integer.

License

Open Source License

Parameter

Parameter Description
buffer Buffer to read from

Return

Integer value

Declaration

public static int readSignedVarint(ByteBuffer buffer) throws IOException 

Method Source Code


//package com.java2s;
/*//from w  ww  . j  a  v  a2s  .  co m
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures
    
 Copyright (C) 2016
 Ludwig-Maximilians-Universit?t M?nchen
 Lehr- und Forschungseinheit f?r Datenbanksysteme
 ELKI Development Team
    
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
    
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.
    
 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.IOException;

import java.nio.ByteBuffer;

public class Main {
    /**
     * Read a signed integer.
     *
     * @param buffer Buffer to read from
     * @return Integer value
     */
    public static int readSignedVarint(ByteBuffer buffer) throws IOException {
        final int raw = readUnsignedVarint(buffer);
        return (raw >>> 1) ^ -(raw & 1);
    }

    /**
     * Read an unsigned integer.
     *
     * @param buffer Buffer to read from
     * @return Integer value
     */
    public static int readUnsignedVarint(ByteBuffer buffer) throws IOException {
        int val = 0;
        int bits = 0;
        while (true) {
            final int data = buffer.get();
            val |= (data & 0x7F) << bits;
            if ((data & 0x80) == 0) {
                return val;
            }
            bits += 7;
            if (bits > 35) {
                throw new IOException("Variable length quantity is too long for expected integer.");
            }
        }
    }
}

Related

  1. readResBit15(ByteBuffer fromBuffer)
  2. readShortLE(ByteBuffer buf, int i)
  3. readShortLength(ByteBuffer bb)
  4. readShorts(final ByteBuffer bb, final int length)
  5. readShortString(ByteBuffer buffer)
  6. readSize(ByteBuffer buf)
  7. readSize(ByteBuffer buffer)
  8. readSmart(ByteBuffer buffer)
  9. readToBytes(ByteBuffer byteBuffer)