Java Integer to Byte Array intToByteArray(final int integer)

Here you can find the source of intToByteArray(final int integer)

Description

Returns a byte array containing the two's-complement representation of the integer.
The byte array will be in big-endian byte-order with a fixes length of 4 (the least significant byte is in the 4th element).

Example:
intToByteArray(258) will return { 0, 0, 1, 2 },
BigInteger.valueOf(258).toByteArray() returns { 1, 2 }.

License

Apache License

Parameter

Parameter Description
integer The integer to be converted.

Return

The byte array of length 4.

Declaration

public static final byte[] intToByteArray(final int integer) 

Method Source Code

//package com.java2s;
/**//from  ww  w.ja v a2 s  .  c om
 *  Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 *  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.
 **/

public class Main {
    /**
     * Returns a byte array containing the two's-complement representation of the integer.<br>
     * The byte array will be in big-endian byte-order with a fixes length of 4
     * (the least significant byte is in the 4th element).<br>
     * <br>
     * <b>Example:</b><br>
     * <code>intToByteArray(258)</code> will return { 0, 0, 1, 2 },<br>
     * <code>BigInteger.valueOf(258).toByteArray()</code> returns { 1, 2 }.
     * @param integer The integer to be converted.
     * @return The byte array of length 4.
     */
    public static final byte[] intToByteArray(final int integer) {
        int byteNum = (40 - Integer.numberOfLeadingZeros(integer < 0 ? ~integer : integer)) / 8;
        byte[] byteArray = new byte[4];

        for (int n = 0; n < byteNum; n++) {
            byteArray[3 - n] = (byte) (integer >>> (n * 8));
        }

        return (byteArray);
    }
}

Related

  1. integerToBytes(int x)
  2. intTo2Bytes(int x)
  3. intTo4ByteArray(int value)
  4. intTo4Bytes(int i)
  5. intToByteArray(byte[] bytes, int i)
  6. intToByteArray(final int integer)
  7. intToByteArray(final int v, final byte[] buf, final int offset)
  8. intToByteArray(final int val, final byte[] buf, final int offset)
  9. intToByteArray(final int value)