Reads the integer from the stream as a 7 bit encoded integer - Java java.io

Java examples for java.io:InputStream Read

Description

Reads the integer from the stream as a 7 bit encoded integer

Demo Code


//package com.java2s;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**//from w ww .j a  v  a  2 s.c  om
     * Reads the integer from the stream as a 7 bit encoded integer
     * @param in The input stream
     * @return The integer read
     * @throws IOException If an IO error occurs
     */
    public static int read7BitEncodedInt(final InputStream in)
            throws IOException {
        //Based on the .NET implementation.  See http://referencesource.microsoft.com/#mscorlib/system/io/binaryreader.cs,569

        //Read out an Int32 7 bits at a time.  The high bit of the byte when on means to continue reading more bytes.
        int count = 0;
        int shift = 0;
        byte b;

        do {
            //Check for a corrupted stream.  Read a max of 5 bytes.
            if (shift == 5 * 7) //5 bytes max per Int32, shift += 7
                throw new IOException("Bad 7 bit encoded integer");

            byte[] bArray = new byte[1];
            if (in.read(bArray) < 0)
                throw new EOFException();

            b = bArray[0];

            //b = (byte) in.read();

            //if (b < 0) //in.read() returns -1 if no bytes were read
            //    throw new EOFException();

            count |= (b & 0x7F) << shift;
            shift += 7;
        } while ((b & 0x80) != 0);

        return count;
    }
}

Related Tutorials