Java ByteBuffer to Int readVarInt(ByteBuffer stream)

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

Description

read Var Int

License

Open Source License

Declaration

public static int readVarInt(ByteBuffer stream) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class Main {
    public static int readVarInt(ByteBuffer stream) throws IOException {
        final byte b[] = new byte[1];
        int count = 0;
        int result = 0;

        do {/*from   w  ww.  j a  v a 2  s . c o  m*/
            if (count == 5) {
                // If we get here it means that the fifth bit had its
                // high bit set, which implies corrupt data.
                throw new IOException("stream corrupted");
            }
            stream.get(b);

            result |= (b[0] & 0x7F) << (7 * count);
            ++count;
        } while ((b[0] & 0x80) > 0);

        return result;
    }

    public static int readVarInt(InputStream stream) throws IOException {
        final byte b[] = new byte[1];
        int count = 0;
        int result = 0;

        do {
            if (count == 5) {
                // If we get here it means that the fifth bit had its
                // high bit set, which implies corrupt data.
                throw new IOException("stream corrupted");
            }
            if (stream.read(b) == -1) {
                throw new IOException("end of stream");
            }
            result |= (b[0] & 0x7F) << (7 * count);
            ++count;
        } while ((b[0] & 0x80) > 0);

        return result;
    }
}

Related

  1. readUnsignedVarint(ByteBuffer buffer)
  2. readVarInt(ByteBuffer buff)
  3. readVarInt(ByteBuffer buff)
  4. readVarint(ByteBuffer buffer)
  5. readVarInt(ByteBuffer buffer)
  6. readVarIntRest(ByteBuffer buff, int b)
  7. toInt(ByteBuffer buffer)
  8. toInt(ByteBuffer buffer)
  9. toInt(ByteBuffer bytes)