Java Byte Array Create toBytes(final long n)

Here you can find the source of toBytes(final long n)

Description

Returns a 8-byte array built from a long.

License

Apache License

Parameter

Parameter Description
n The number to convert.

Return

A byte[].

Declaration

public static byte[] toBytes(final long n) 

Method Source Code

//package com.java2s;
/**/*from  www .ja va2  s  .c o m*/
 * Copyright 2003-2004 The Apache Software Foundation. Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed
 * to in writing, software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under the
 * License.
 * <p>
 * Static methods for managing byte arrays (all methods follow Big Endian order where most
 * significant bits are in front).
 * </p>
 * 
 * @author Commons-Id Team
 * @version $Id: Bytes.java,v 1.1 2004/05/31 06:54:24 treilly Exp $ {@link http
 *          ://jakarta.apache.org/turbine/turbine-2.3/}
 */

public class Main {
    /**
     * Returns a 8-byte array built from a long.
     * 
     * @param n
     *            The number to convert.
     * @return A byte[].
     */
    public static byte[] toBytes(final long n) {
        return toBytes(n, new byte[8]);
    }

    /**
     * Build a 8-byte array from a long. No check is performed on the array length.
     * 
     * @param n
     *            The number to convert.
     * @param b
     *            The array to fill.
     * @return A byte[].
     */
    public static byte[] toBytes(final long n, final byte[] b) {
        long n2 = n;
        b[7] = (byte) (n2);
        n2 >>>= 8;
        b[6] = (byte) (n2);
        n2 >>>= 8;
        b[5] = (byte) (n2);
        n2 >>>= 8;
        b[4] = (byte) (n2);
        n2 >>>= 8;
        b[3] = (byte) (n2);
        n2 >>>= 8;
        b[2] = (byte) (n2);
        n2 >>>= 8;
        b[1] = (byte) (n2);
        n2 >>>= 8;
        b[0] = (byte) (n2);

        return b;
    }
}

Related

  1. toBytes(char c)
  2. toBytes(char value)
  3. toBytes(char[] cbuf, byte[] bs)
  4. toBytes(char[] chars)
  5. toBytes(final byte[] s, final int off, final int len)
  6. toBytes(final long val)
  7. toBytes(final String hexaString)
  8. toBytes(final String str)
  9. toBytes(final String text)