Java Byte Array Create toBytes(byte[] b, int offset, long val)

Here you can find the source of toBytes(byte[] b, int offset, long val)

Description

Convert a long value to a byte array using big-endian.

License

Open Source License

Parameter

Parameter Description
b the b
offset the offset
val value to convert

Return

the byte array

Declaration

public static byte[] toBytes(byte[] b, int offset, long val) 

Method Source Code

//package com.java2s;
/*******************************************************************************
* Copyright (c) 2013 Vladimir Rodionov. All Rights Reserved
*
* This code is released under the GNU Affero General Public License.
*
* See: http://www.fsf.org/licensing/licenses/agpl-3.0.html
*
* VLADIMIR RODIONOV MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY
* OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. Vladimir Rodionov SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
* BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR
* ITS DERIVATIVES.//from ww  w .  j  a va2  s  . co m
*
* Author: Vladimir Rodionov
*
*******************************************************************************/

public class Main {
    /**
     * Convert a long value to a byte array using big-endian.
     *
     * @param b the b
     * @param offset the offset
     * @param val value to convert
     * @return the byte array
     */
    public static byte[] toBytes(byte[] b, int offset, long val) {

        for (int i = offset + 7; i > offset; i--) {
            b[i] = (byte) val;
            val >>>= 8;
        }
        b[offset] = (byte) val;
        return b;
    }

    /**
     * To bytes.
     *
     * @param b the b
     * @param offset the offset
     * @param val the val
     * @return the byte[]
     */
    public static byte[] toBytes(byte[] b, int offset, int val) {

        for (int i = offset + 3; i > offset; i--) {
            b[i] = (byte) val;
            val >>>= 8;
        }
        b[offset] = (byte) val;
        return b;
    }
}

Related

  1. toByteArrayV4(String address)
  2. toByteArrayV6(String address)
  3. toByteInfo(long bytes)
  4. toBytes(boolean[] input)
  5. toBytes(byte data)
  6. toBytes(byte[] buffer, int pos, String string)
  7. toBytes(byte[] ipAddress, int port)
  8. toBytes(Byte[] values)
  9. toBytes(char c)