Java Utililty Methods Long to Byte Array

List of utility methods to do Long to Byte Array

Description

The list of methods to do Long to Byte Array are organized into topic(s).

Method

byte[]longToBytes(long l)
long To Bytes
byte[] b = new byte[8];
b[0] = (byte) (l >>> 56);
b[1] = (byte) (l >>> 48);
b[2] = (byte) (l >>> 40);
b[3] = (byte) (l >>> 32);
b[4] = (byte) (l >>> 24);
b[5] = (byte) (l >>> 16);
b[6] = (byte) (l >>> 8);
...
byte[]longToBytes(long l)
Converts primitive long type to byte array.
return toBytes(l, new byte[8], 0, 8);
byte[]longToBytes(long l)
This function converts a long to its corresponding byte array format.
byte[] buffer = new byte[8];
longToBytes(l, buffer, 0);
return buffer;
voidlongToBytes(long l, byte[] arr, int startIdx)
Unsigned Long to 8 bytes
if (arr == null) {
    return;
int idx = startIdx;
arr[idx++] = (byte) ((l >>> 56) & 0x00000000000000ff);
arr[idx++] = (byte) ((l >>> 48) & 0x00000000000000ff);
arr[idx++] = (byte) ((l >>> 40) & 0x00000000000000ff);
arr[idx++] = (byte) ((l >>> 32) & 0x00000000000000ff);
...
voidlongToBytes(long l, byte[] b)
long To Bytes
if (b.length < 8) {
    throw new IllegalArgumentException("Byte array should contain at least 8bytes ");
for (int i = 7; i >= 0; i--) {
    b[i] = (byte) (l >>> (8 * i));
voidlongToBytes(long l, byte[] bytes, int offset)
long To Bytes
bytes[offset + 0] = (byte) ((l & 0xFF00000000000000L) >> 56);
bytes[offset + 1] = (byte) ((l & 0x00FF000000000000L) >> 48);
bytes[offset + 2] = (byte) ((l & 0x0000FF0000000000L) >> 40);
bytes[offset + 3] = (byte) ((l & 0x000000FF00000000L) >> 32);
bytes[offset + 4] = (byte) ((l & 0x00000000FF000000L) >> 24);
bytes[offset + 5] = (byte) ((l & 0x0000000000FF0000L) >> 16);
bytes[offset + 6] = (byte) ((l & 0x000000000000FF00L) >> 8);
bytes[offset + 7] = (byte) ((l & 0x00000000000000FFL));
...
voidlongToBytes(long l, byte[] data, int[] offset)
Write the bytes representing l into the byte array data, starting at index offset [0], and increment offset [0] by the number of bytes written; if data == null, increment offset [0] by the number of bytes that would have been written otherwise.
if (data != null) {
    for (int j = (offset[0] + SIZE_LONG) - 1; j >= offset[0]; --j) {
        data[j] = (byte) l;
        l >>= 8;
offset[0] += SIZE_LONG;
byte[]longToBytes(long l, byte[] result)
long To Bytes
for (int i = Long.BYTES - 1; i >= 0; i--) {
    result[i] = (byte) (l & 0xFF);
    l >>= Byte.SIZE;
return result;
byte[]longToBytes(long ldata, int n)
Convert 64 bit long to n bytes.
byte[] buff = new byte[n];
for (int i = n - 1; i >= 0; i--) {
    buff[i] = (byte) ldata;
    ldata = ldata >> 8;
return buff;
intlongToBytes(long lnum, byte[] bytes, int startIndex)
Given a long, convert it into a byte array
for (int i = 0; i < 8; i++)
    bytes[startIndex + i] = (byte) ((lnum >> (i * 8)) & 0xff);
return startIndex + 8;