Java Integer to Byte Array intToByteArray(final int integer)

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

Description

int To Byte Array

License

Apache License

Declaration

public static byte[] intToByteArray(final int integer) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static 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);
    }//  w  ww.j av  a  2s . co  m

    public static byte[] intToByteArray(final int num, int length) {
        byte[] byteArray = intToByteArray(num);
        byte[] result = new byte[length];
        for (int i = 0; i < length; i++) {
            result[i] = byteArray[4 - i - 1];
        }
        return result;
    }
}

Related

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