Reads an integer from the byte array starting from the given offset. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Reads an integer from the byte array starting from the given offset.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        System.out.println(readInt(b, offset));
    }/*  w ww.  ja  v  a  2  s .c o m*/

    /**
     * Reads an integer from the byte array starting from the given offset.
     */
    public static int readInt(byte[] b, int offset) {
        if (b.length < offset + 4) {
            throw new ArrayIndexOutOfBoundsException(
                    "byte array has less than 4 bytes from offset: "
                            + offset);
        }
        int v = (b[offset] & 0xFF) << 24;
        v += (b[offset + 1] & 0xFF) << 16;
        v += (b[offset + 2] & 0xFF) << 8;
        v += (b[offset + 3] & 0xFF) << 0;

        return v;
    }
}

Related Tutorials