Retrieve an int from the binary format. - Java java.lang

Java examples for java.lang:int Format

Description

Retrieve an int from the binary format.

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    /**//ww w.  j  a va2  s  .  c o m
     * Retrieve and int from the binary format.
     * @param fin
     * @return
     * @throws IOException 
     */
    public static int getInt(final InputStream fin) throws IOException {
        byte[] buffer = new byte[4];
        ByteBuffer bb = ByteBuffer.wrap(buffer);
        if (fin.read(buffer) < 0) {
            throw new IOException("EOF");
        }
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.position(0);
        return bb.getInt();
    }

    /**
     * Convert any length of bytes to an integer.
     * @param fin
     * @param byteCount
     * @return
     * @throws IOException 
     */
    public static int getInt(final InputStream fin, final int byteCount)
            throws IOException {
        byte[] buffer = new byte[byteCount];
        ByteBuffer bb = ByteBuffer.wrap(buffer);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        if (fin.read(buffer) < 0) {
            throw new IOException("EOF");
        }
        bb.position(0);
        int i = 0;
        for (byte b : bb.array()) {
            i += b;
        }
        i = i & 0xff;
        return i;
    }
}

Related Tutorials