Reconstructs a long from bytes - Java java.lang

Java examples for java.lang:byte array to long

Description

Reconstructs a long from bytes

Demo Code

/******************************************************************************
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this
 * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  ww  w . j  a  v a  2s  .  c o  m
 * Aggregate Knowledge - implementation
 ******************************************************************************/
//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(bytesToLong(array, offset));
    }

    /**
     * Reconstructs a <code>long</code> from <code>byte</code>s that was encoded
     * with {@link #longToBytes(long, byte[], int)}.
     *
     * @param  array the array of bytes
     * @param  offset the offset in <code>array</code> to start reading from
     * @return the encoded <code>long</code>
     */
    public static long bytesToLong(byte[] array, int offset) {
        long value = (long) array[offset + 0] & 0x00000000000000ff;
        value = (value << 8) | (array[offset + 1] & 0x00000000000000ff);
        value = (value << 8) | (array[offset + 2] & 0x00000000000000ff);
        value = (value << 8) | (array[offset + 3] & 0x00000000000000ff);
        value = (value << 8) | (array[offset + 4] & 0x00000000000000ff);
        value = (value << 8) | (array[offset + 5] & 0x00000000000000ff);
        value = (value << 8) | (array[offset + 6] & 0x00000000000000ff);
        value = (value << 8) | (array[offset + 7] & 0x00000000000000ff);

        return value;
    }
}

Related Tutorials