Java Long to Byte Array longToBytes(final long aLong)

Here you can find the source of longToBytes(final long aLong)

Description

long To Bytes

License

Open Source License

Parameter

Parameter Description
aLong a parameter

Declaration

public static byte[] longToBytes(final long aLong) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2011 www.isandlatech.com (www.isandlatech.com)
 * All rights reserved. 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:// www.j  av a 2s. c  o  m
 *    ogattaz (isandlaTech) - initial API and implementation
 *******************************************************************************/

public class Main {
    public static final int LEN_OF_LONG = 8;
    private static final String MESS_NOT_ENOUGH_LARGE = "The byte array is not enough large. It should have at least [%s] bytes to accept an [%s]";

    /**
     * @param aLong
     * @return
     */
    public static byte[] longToBytes(final long aLong) {
        byte[] wBuffer = new byte[LEN_OF_LONG];
        appendLongInBuffer(wBuffer, 0, aLong);
        return wBuffer;
    }

    /**
     * Ajoute un "long" 8 octets au buffer.
     * 
     * @param aBuffer
     * @param aPos
     * @param aValue
     * @return la nouvelle position
     * @throws IllegalArgumentException
     */
    public static int appendLongInBuffer(final byte[] aBuffer,
            final int aPos, final long aValue)
            throws IllegalArgumentException {
        if (aBuffer.length - aPos < LEN_OF_LONG) {
            throw new IllegalArgumentException(builNotEnoughLargeMess(
                    LEN_OF_LONG, "long"));
        }

        for (int i = 7; i >= 0; i--) {
            aBuffer[aPos + 7 - i] = (byte) (aValue >>> (8 * i));
        }
        return aPos + LEN_OF_LONG;
    }

    /**
     * @param aSize
     * @param aContent
     * @return
     */
    private static String builNotEnoughLargeMess(final int aSize,
            final String aContent) {
        return String.format(MESS_NOT_ENOUGH_LARGE, String.valueOf(aSize),
                aContent);
    }
}

Related

  1. longToByteArray6(long addr)
  2. longToByteArrayBE(long data)
  3. longToByteArrayForAS(long i)
  4. longToByteBounds(long value)
  5. longToBytes(byte[] arr, int offset, long num)
  6. longToBytes(final long l)
  7. longToBytes(final long l)
  8. longToBytes(final long val)
  9. longToBytes(final long value)