Java Integer to Byte Array intToByteArray(int i)

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

Description

converts an int to an array of bytes.

License

Apache License

Parameter

Parameter Description
i the int to convert.

Declaration

public static byte[] intToByteArray(int i) 

Method Source Code

//package com.java2s;
/**/*w  ww  .ja  va  2  s.  co m*/
 * Appia: Group communication and protocol composition framework library
 * Copyright 2006 University of Lisbon
 *
 * 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. 
 *
 * Initial developer(s): Alexandre Pinto and Hugo Miranda.
 * Contributor(s): See Appia web page for a list of contributors.
 */

public class Main {
    /**
     * converts an int to an array of bytes.
     * @param i the int to convert.
     */
    public static byte[] intToByteArray(int i) {
        byte[] ret = new byte[4];

        ret[0] = (byte) ((i & 0xff000000) >> 24);
        ret[1] = (byte) ((i & 0x00ff0000) >> 16);
        ret[2] = (byte) ((i & 0x0000ff00) >> 8);
        ret[3] = (byte) (i & 0x000000ff);

        return ret;
    }

    /**
     * Convert an int to a byte array and put the bytes in the given array.
     * @param i the int to convert.
     * @param a the byte array where to place the converted bytes
     * @param o the offset.
     */
    public static void intToByteArray(int i, byte[] a, int o) {
        a[o + 0] = (byte) ((i & 0xff000000) >> 24);
        a[o + 1] = (byte) ((i & 0x00ff0000) >> 16);
        a[o + 2] = (byte) ((i & 0x0000ff00) >> 8);
        a[o + 3] = (byte) (i & 0x000000ff);
    }
}

Related

  1. intToByteArray(int a)
  2. intToByteArray(int a)
  3. intToByteArray(int bytes)
  4. intToByteArray(int data)
  5. intToByteArray(int i)
  6. intToByteArray(int input)
  7. intToByteArray(int integer)
  8. intToByteArray(int integer)
  9. intToByteArray(int piValueToConvert, boolean pbBigEndian)