Java Long to Byte Array long2Bytes(long num)

Here you can find the source of long2Bytes(long num)

Description

Convert long to bytes, for small integer, only low-digits are stored in bytes, and all high zero digits are removed to save memory.

License

Open Source License

Declaration

public static byte[] long2Bytes(long num) 

Method Source Code

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

public class Main {
    /**// w  w  w.ja  va 2 s.  c  o m
     * Convert long to bytes, for small integer, only low-digits are stored in
     * bytes, and all high zero digits are removed to save memory. For example:
     * number 1 should convert to one byte [00000001], number 130
     * should convert to two bytes [00000001, 00000010]
     * @return
     */
    public static byte[] long2Bytes(long num) {
        byte[] buffer = new byte[8];
        for (int ix = 0; ix < 8; ++ix) {
            int offset = 64 - (ix + 1) * 8;
            buffer[ix] = (byte) ((num >> offset) & 0xff);
        }

        int i = 0;
        for (i = 0; i < buffer.length - 1; i++) {
            byte b = buffer[i];
            if (b != 0) {
                break;
            }
        }

        //remove zero high bytes
        byte[] buffer2 = new byte[8 - i];
        for (int j = 0; j < buffer2.length; j++) {
            buffer2[j] = buffer[i + j];
        }
        return buffer2;
    }
}

Related

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