Java Byte Array Create toBytes(int i)

Here you can find the source of toBytes(int i)

Description

Convert an integer value into an byte array.

License

Open Source License

Parameter

Parameter Description
i An integer value.

Return

A converted byte array.

Declaration

public static byte[] toBytes(int i) 

Method Source Code

//package com.java2s;
/*/* w w w .  j ava  2s  .  c  om*/
 * Copyright (c) 2015 NEC Corporation
 * All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this
 * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html
 */

public class Main {
    /**
     * The number of octets in an integer value.
     */
    public static final int NUM_OCTETS_INTEGER = Integer.SIZE / Byte.SIZE;
    /**
     * The number of bits to be shifted to get the first octet in an integer.
     */
    private static final int INT_SHIFT_OCTET1 = 24;
    /**
     * The number of bits to be shifted to get the second octet in an integer.
     */
    private static final int INT_SHIFT_OCTET2 = 16;
    /**
     * The number of bits to be shifted to get the third octet in an integer.
     */
    private static final int INT_SHIFT_OCTET3 = 8;

    /**
     * Convert an integer value into an byte array.
     *
     * @param i  An integer value.
     * @return   A converted byte array.
     */
    public static byte[] toBytes(int i) {
        byte[] b = new byte[NUM_OCTETS_INTEGER];
        setInt(b, 0, i);
        return b;
    }

    /**
     * Set an integer value into the given byte array in network byte order.
     *
     * @param array  A byte array.
     * @param off    Index of {@code array} to store value.
     * @param value  An integer value.
     */
    public static void setInt(byte[] array, int off, int value) {
        int index = off;
        array[index++] = (byte) (value >>> INT_SHIFT_OCTET1);
        array[index++] = (byte) (value >>> INT_SHIFT_OCTET2);
        array[index++] = (byte) (value >>> INT_SHIFT_OCTET3);
        array[index] = (byte) value;
    }
}

Related

  1. toBytes(int i)
  2. toBytes(int i)
  3. toBytes(int i)
  4. toBytes(int i)
  5. toBytes(int i)
  6. toBytes(int integer)
  7. toBytes(int integer)
  8. toBytes(int intValue)
  9. toBytes(int is)