Java Long to Byte Array longToBytes(long l)

Here you can find the source of longToBytes(long l)

Description

Converts primitive long type to byte array.

License

GNU General Public License

Parameter

Parameter Description
l Long value.

Return

Array of bytes.

Declaration

public static byte[] longToBytes(long l) 

Method Source Code

//package com.java2s;
// Copyright (C) GridGain Systems Licensed under GPLv3, http://www.gnu.org/licenses/gpl.html

public class Main {
    /**/*w  w w. j a  v  a 2 s.c o m*/
     * Converts primitive {@code long} type to byte array.
     *
     * @param l Long value.
     * @return Array of bytes.
     */
    public static byte[] longToBytes(long l) {
        return toBytes(l, new byte[8], 0, 8);
    }

    /**
     * Converts primitive {@code long} type to byte array and stores it in specified
     * byte array.
     *
     * @param l Long value.
     * @param bytes Array of bytes.
     * @param off Offset in {@code bytes} array.
     * @return Number of bytes overwritten in {@code bytes} array.
     */
    public static int longToBytes(long l, byte[] bytes, int off) {
        toBytes(l, bytes, off, 8);

        return 8;
    }

    /**
     * Converts primitive {@code long} type to byte array and stores it in specified
     * byte array. The highest byte in the value is the first byte in result array.
     *
     * @param l Unsigned long value.
     * @param bytes Bytes array to write result to.
     * @param offset Offset in the target array to write result to.
     * @param limit Limit of bytes to write into output.
     * @return Number of bytes overwritten in {@code bytes} array.
     */
    private static byte[] toBytes(long l, byte[] bytes, int offset, int limit) {
        assert bytes != null;
        assert limit <= 8;
        assert bytes.length >= offset + limit;

        for (int i = limit - 1; i >= 0; i--) {
            bytes[offset + i] = (byte) (l & 0xFF);
            l >>>= 8;
        }

        return bytes;
    }
}

Related

  1. longToBytes(final long l)
  2. longToBytes(final long val)
  3. longToBytes(final long value)
  4. longToBytes(long data)
  5. longToBytes(long k, byte[] b, int i)
  6. longToBytes(long l)
  7. longToBytes(long l)
  8. longToBytes(long l, byte[] arr, int startIdx)
  9. longToBytes(long l, byte[] b)