Java Long to Byte Array longToBytes(long l)

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

Description

This function converts a long to its corresponding byte array format.

License

Open Source License

Parameter

Parameter Description
l The long to be converted.

Return

The corresponding byte array.

Declaration

static public byte[] longToBytes(long l) 

Method Source Code

//package com.java2s;
/************************************************************************
 * Copyright (c) Crater Dog Technologies(TM).  All Rights Reserved.     *
 ************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.        *
 *                                                                      *
 * This code is free software; you can redistribute it and/or modify it *
 * under the terms of The MIT License (MIT), as published by the Open   *
 * Source Initiative. (See http://opensource.org/licenses/MIT)          *
 ************************************************************************/

public class Main {
    /**/* ww w  .  ja va 2s . c o m*/
     * This function converts a long to its corresponding byte array format.
     *
     * @param l The long to be converted.
     * @return The corresponding byte array.
     */
    static public byte[] longToBytes(long l) {
        byte[] buffer = new byte[8];
        longToBytes(l, buffer, 0);
        return buffer;
    }

    /**
     * This function converts a long into its corresponding byte format and inserts
     * it into the specified buffer.
     *
     * @param l The long to be converted.
     * @param buffer The byte array.
     * @return The number of bytes inserted.
     */
    static public int longToBytes(long l, byte[] buffer) {
        return longToBytes(l, buffer, 0);
    }

    /**
     * This function converts a long into its corresponding byte format and inserts
     * it into the specified buffer at the specified index.
     *
     * @param l The long to be converted.
     * @param buffer The byte array.
     * @param index The index in the array to begin inserting bytes.
     * @return The number of bytes inserted.
     */
    static public int longToBytes(long l, byte[] buffer, int index) {
        int length = buffer.length - index;
        if (length > 8)
            length = 8;
        for (int i = 0; i < length; i++) {
            buffer[index + length - i - 1] = (byte) (l >> (i * 8));
        }
        return length;
    }
}

Related

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