Writes a long as bytes into the provided array. - Java java.lang

Java examples for java.lang:byte Array to int

Description

Writes a long as bytes into the provided array.

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 www. 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 {
        long value = 2;
        byte[] array = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        int offset = 2;
        longToBytes(value, array, offset);
    }

    /**
     * Writes a <code>long</code> as <code>byte</code>s into the provided array.
     * @param value the <code>long</code> to encode
     * @param array the write target
     * @param offset the offset in the array at which to write <code>value</code>
     */
    public static void longToBytes(long value, byte[] array, int offset) {
        array[offset + 0] = (byte) (0xff & (value >> 56));
        array[offset + 1] = (byte) (0xff & (value >> 48));
        array[offset + 2] = (byte) (0xff & (value >> 40));
        array[offset + 3] = (byte) (0xff & (value >> 32));
        array[offset + 4] = (byte) (0xff & (value >> 24));
        array[offset + 5] = (byte) (0xff & (value >> 16));
        array[offset + 6] = (byte) (0xff & (value >> 8));
        array[offset + 7] = (byte) (0xff & value);
    }
}

Related Tutorials