Converts an array of bytes to an integer. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts an array of bytes to an integer.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte data = 2;
        System.out.println(bytesToInt(data));
    }//from   ww w.  j  a v a 2s.c  o  m

    /**
     * <p>
     * Converts an array of bytes to an integer. If there are more than four bytes, the first four bytes in the array are used and
     * the rest are ignored.<br>
     * </p>
     * 
     * @param data
     *            The byte array to be converted to an integer.
     * @return The integer equivalent of the given byte array.
     */
    public static int bytesToInt(byte... data) {
        byte[] tmp = data;
        if (data.length < 4) {
            tmp = new byte[] { 0, 0, 0, 0 };
            System.arraycopy(data, 0, tmp, 0, data.length);
        }

        return ((tmp[3] & 0xFF) << 24 | (tmp[2] & 0xFF) << 16
                | (tmp[1] & 0xFF) << 8 | tmp[0] & 0xFF);
    }
}

Related Tutorials