Reads a long from the byte array starting from the given offset. - Java java.lang

Java examples for java.lang:byte array to long

Description

Reads a long 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(readLong(b, offset));
    }//  w  w w. j  a  v a2 s  .co m

    /**
     * Reads a long from the byte array starting from the given offset.
     */
    public static long readLong(byte[] b, int offset) {
        if (b.length < offset + 8) {
            throw new ArrayIndexOutOfBoundsException(
                    "byte array has less than 8 bytes from offset: "
                            + offset);
        }
        long v = (b[offset] & 0xFFL) << 56;
        v += (b[offset + 1] & 0xFFL) << 48;
        v += (b[offset + 2] & 0xFFL) << 40;
        v += (b[offset + 3] & 0xFFL) << 32;
        v += (b[offset + 4] & 0xFFL) << 24;
        v += (b[offset + 5] & 0xFFL) << 16;
        v += (b[offset + 6] & 0xFFL) << 8;
        v += (b[offset + 7] & 0xFFL) << 0;

        return v;
    }
}

Related Tutorials