Java Integer to Byte Array int32ToByteArray(int a)

Here you can find the source of int32ToByteArray(int a)

Description

int To Byte Array

License

Apache License

Declaration

public static byte[] int32ToByteArray(int a) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2015 InfinitiesSoft Solutions Inc.
 *
 * 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/*from w  w  w.  j av  a  2s .c om*/
 *
 *      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 {
    public static byte[] int32ToByteArray(int a) {
        byte[] ret = new byte[4];
        ret[0] = (byte) (a & 0xFF);
        ret[1] = (byte) ((a >> 8) & 0xFF);
        ret[2] = (byte) ((a >> 16) & 0xFF);
        ret[3] = (byte) ((a >> 24) & 0xFF);
        return ret;
    }

    public static byte[] int32ToByteArray(long a) {
        byte[] ret = new byte[4];
        ret[0] = (byte) (a & 0xFF);
        ret[1] = (byte) ((a >> 8) & 0xFF);
        ret[2] = (byte) ((a >> 16) & 0xFF);
        ret[3] = (byte) ((a >> 24) & 0xFF);
        return ret;
    }

    private static byte[] int32ToByteArray(int[] data) {
        byte[] ret = new byte[data.length * 4];
        int retIndex = 0;
        for (int i = 0; i < data.length; i++) {
            byte[] array = int32ToByteArray(data[i]);
            ret[retIndex++] = array[0];
            ret[retIndex++] = array[1];
            ret[retIndex++] = array[2];
            ret[retIndex++] = array[3];
        }
        return ret;
    }
}

Related

  1. int2bytes(int... numbers)
  2. int2bytes2(int src, byte[] dest)
  3. int32ToArray(int data)
  4. int32ToArrayInPlace(int data, byte[] buffer, int offset)
  5. int32ToByteArr(int val, byte[] arr, int offset)
  6. int32toByteArray(int i)
  7. int32ToByteArray(int integer)
  8. int32ToByteArray(int value)
  9. integerToByteArray(final int integerToSerialize, final byte[] byteArray, final int offset)