Reads a UInt32 from the InputStream and returns it as a Java int. - Java java.io

Java examples for java.io:InputStream Read

Description

Reads a UInt32 from the InputStream and returns it as a Java int.

Demo Code


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

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    /**//ww w.ja  va2s.  c  om
     * Reads a UInt32 from the stream and returns it as a Java int.
     * @param in The input stream
     * @return A UInt32 as a Java int.
     * @throws IOException If an IO error occurs
     */
    public static int readUInt32(final InputStream in) throws IOException {
        byte[] buffer = new byte[4];
        ByteBuffer bb = ByteBuffer.wrap(buffer);

        if (in.read(buffer) < 0) //Read the stream into the buffer
            throw new EOFException();

        //Switch the byte ordering to little endian, which is what .NET uses
        bb.order(ByteOrder.LITTLE_ENDIAN);
        bb.position(0);

        return bb.getInt();
    }
}

Related Tutorials