Get a long from 8 bytes of the given array at offset 0. - Java java.lang

Java examples for java.lang:byte array to long

Description

Get a long from 8 bytes of the given array at offset 0.

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 };
        System.out.println(bytes2long(b));
    }// w  w  w.  j  av a2 s . c o m

    /**
     * Get a long from 8 bytes of the given array at offset 0.
     * 
     * @param b byte array
     * @return a short
     */
    public static final long bytes2long(byte[] b) {
        return bytes2long(b, 0);
    }

    /**
     * Get a long from 8 bytes of the given array at specific offset.
     * 
     * @param b byte array
     * @param off offset of the byte array
     * @return a short
     */
    public static final long bytes2long(byte[] b, int off) {
        return (((long) b[off]) << 56 | ((long) (b[off + 1] & 0xff)) << 48
                | ((long) (b[off + 2]) & 0xff) << 40
                | ((long) (b[off + 3]) & 0xff) << 32
                | (((long) b[off + 4]) & 0xff) << 24
                | (((long) b[off + 5]) & 0xff) << 16
                | (((long) b[off + 6]) & 0xff) << 8 | (((long) b[off + 7]) & 0xff));
    }
}

Related Tutorials