Converts a byte array that represents an signed 32-bit integer - Java java.lang

Java examples for java.lang:byte Array Convert

Description

Converts a byte array that represents an signed 32-bit integer

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] bytes = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(toLong(bytes));
    }/*from   www.  ja v a 2  s.c om*/

    /**
     * Converts a byte array that represents an signed 32-bit
     * integer
     */
    public static long toLong(byte[] bytes) {
        if (bytes.length != 8) {
            throw new IllegalArgumentException("Must be 8 bytes");
        }

        long value1 = bytes[3] & 0xFF;
        value1 |= ((bytes[2] << 8) & 0xFF00);
        value1 |= ((bytes[1] << 16) & 0xFF0000);
        value1 |= ((bytes[0] << 24) & 0xFF000000);

        long value2 = bytes[7] & 0xFF;
        value2 |= ((bytes[6] << 8) & 0xFF00);
        value2 |= ((bytes[5] << 16) & 0xFF0000);
        value2 |= ((bytes[4] << 24) & 0xFF000000);
        return ((long) (value1 << 32) + (value2 & 0xFFFFFFFFL));

    }
}

Related Tutorials