Java Long to Byte Array longToBytes(long ldata, int n)

Here you can find the source of longToBytes(long ldata, int n)

Description

Convert 64 bit long to n bytes.

License

Open Source License

Parameter

Parameter Description
ldata The long from which the n byte array will be constructed.
n The desired number of bytes to convert the long to.

Return

The desired byte array which is populated with the long value.

Declaration

public static synchronized byte[] longToBytes(long ldata, int n) 

Method Source Code

//package com.java2s;
/* //ww  w .j ava 2s.c  om
 * Copyright (C) 2004-2008  University of Wisconsin-Madison and Omnitor AB
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

public class Main {
    /**
     * Convert 64 bit long to n bytes.
     *
     * @param ldata   The long from which the n byte array will be constructed.
     * @param n       The desired number of bytes to convert the long to.
     *
     * @return The desired byte array which is populated with the long value.
     */
    public static synchronized byte[] longToBytes(long ldata, int n) {
        byte[] buff = new byte[n];

        for (int i = n - 1; i >= 0; i--) {
            // Keep assigning the right most 8 bits to the
            // byte arrays while shift 8 bits during each iteration
            buff[i] = (byte) ldata;
            ldata = ldata >> 8;
        }
        return buff;
    }
}

Related

  1. longToBytes(long l, byte[] arr, int startIdx)
  2. longToBytes(long l, byte[] b)
  3. longToBytes(long l, byte[] bytes, int offset)
  4. longToBytes(long l, byte[] data, int[] offset)
  5. longToBytes(long l, byte[] result)
  6. longToBytes(long lnum, byte[] bytes, int startIndex)
  7. longToBytes(long n)
  8. longToBytes(long n)
  9. longToBytes(long n, byte b[], int offset)