Converts an array of bytes to a long. - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts an array of bytes to a long.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte data = 2;
        System.out.println(bytesToLong(data));
    }/*from   w w w. ja  v  a  2 s. co m*/

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

        return ((tmp[7] & 0xFFL) << 56L | (tmp[6] & 0xFFL) << 48L
                | (tmp[5] & 0xFFL) << 40L | (tmp[4] & 0xFFL) << 32L
                | (tmp[3] & 0xFFL) << 24L | (tmp[2] & 0xFFL) << 16L
                | (tmp[1] & 0xFFL) << 8L | tmp[0] & 0xFFL);
    }
}

Related Tutorials