Java Long to Byte Array long2bytes(long i, int byteCount)

Here you can find the source of long2bytes(long i, int byteCount)

Description

longbytes

License

Open Source License

Parameter

Parameter Description
byteCount a number between 0 and 8, the size of the resulting array

Exception

Parameter Description
NegativeArraySizeException if byteCount < 0
ArrayIndexOutOfBoundsException if byteCount > 8

Return

a big-endian array of byteCount bytes matching the passed-in number: ie: 1L,4 becomes -> [0,0,0,1]

Declaration

public static byte[] long2bytes(long i, int byteCount) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//  w ww .j  av a 2  s.  c  o  m
     * @return a big-endian array of byteCount bytes matching the passed-in number: ie: 1L,4 becomes
     *         -> [0,0,0,1]
     * @param byteCount a number between 0 and 8, the size of the resulting array
     * @throws NegativeArraySizeException if byteCount < 0
     * @throws ArrayIndexOutOfBoundsException if byteCount > 8
     */
    public static byte[] long2bytes(long i, int byteCount) {
        byte[] b = new byte[8];
        b[7] = (byte) (i);
        i >>>= 8;
        b[6] = (byte) (i);
        i >>>= 8;
        b[5] = (byte) (i);
        i >>>= 8;
        b[4] = (byte) (i);
        i >>>= 8;
        b[3] = (byte) (i);
        i >>>= 8;
        b[2] = (byte) (i);
        i >>>= 8;
        b[1] = (byte) (i);
        i >>>= 8;
        b[0] = (byte) (i);

        // We have an 8 byte array. Copy the interesting bytes into our new
        // array of size 'byteCount'
        byte[] bytes = new byte[byteCount];
        System.arraycopy(b, 8 - byteCount, bytes, 0, byteCount);
        return bytes;
    }
}

Related

  1. long2ByteArray(long l)
  2. long2ByteArray(long srcValue, int len)
  3. long2ByteLE(byte[] bytes, long value, int offset)
  4. long2bytes(long i)
  5. long2bytes(long i, int byteCount)
  6. long2bytes(long l, byte[] data, int offset)
  7. long2Bytes(long l, byte[] target, int offset)
  8. long2bytes(long longValue)
  9. long2bytes(long num)