Read a long from the byte array at the given offset. - Java java.lang

Java examples for java.lang:byte array to long

Description

Read a long from the byte array at the given offset.

Demo Code


//package com.java2s;

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

    /**
     * Read a long from the byte array at the given offset.
     * 
     * @param array Array to read from
     * @param offset Offset to read at
     * @return data
     */
    public final static long readLong(byte[] array, int offset) {
        // First make integers to resolve signed vs. unsigned issues.
        long b0 = array[offset + 0];
        long b1 = array[offset + 1] & 0xFF;
        long b2 = array[offset + 2] & 0xFF;
        long b3 = array[offset + 3] & 0xFF;
        long b4 = array[offset + 4] & 0xFF;
        int b5 = array[offset + 5] & 0xFF;
        int b6 = array[offset + 6] & 0xFF;
        int b7 = array[offset + 7] & 0xFF;
        return ((b0 << 56) + (b1 << 48) + (b2 << 40) + (b3 << 32)
                + (b4 << 24) + (b5 << 16) + (b6 << 8) + (b7 << 0));
    }
}

Related Tutorials