Java Integer to Byte Array intToByteArray(int value, int numBytes)

Here you can find the source of intToByteArray(int value, int numBytes)

Description

int To Byte Array

License

Open Source License

Declaration

public static byte[] intToByteArray(int value, int numBytes) 

Method Source Code

//package com.java2s;
/*//from w w  w  .  ja  v a2 s . c o m
 *  Copyright (c) 2016 Jose-Juan Pedreno-Manresa, Jose-Luis Izquierdo-Zaragoza, Pablo Pavon-Marino
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the GNU Lesser Public License v3
 *  which accompanies this distribution, and is available at
 *  http://www.gnu.org/licenses/lgpl.html
 *
 *  Contributors:
 *          Jose-Juan Pedreno-Manresa
 *          Jose-Luis Izquierdo-Zaragoza
 */

public class Main {
    public static byte[] intToByteArray(int value, int numBytes) {
        if (numBytes < 1 || numBytes > 4)
            throw new RuntimeException("Bad");

        byte[] actualByteArray = new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8),
                (byte) value };
        byte[] out = new byte[numBytes];
        System.arraycopy(actualByteArray, 4 - numBytes, out, 0, numBytes);

        return out;
    }
}

Related

  1. intToByteArray(int value)
  2. intToByteArray(int value, byte[] buffer, int offset)
  3. intToByteArray(int value, byte[] data, int offset)
  4. intToByteArray(int value, byte[] dest)
  5. intToByteArray(int value, int nrOfBytes)
  6. intToByteArray2(final int integer)
  7. intToByteArray4(int i)
  8. intToByteArray4(int value)
  9. intToByteArrayBE(int data)