Java Integer to Byte Array intToBytes(int val)

Here you can find the source of intToBytes(int val)

Description

int To Bytes

License

Open Source License

Declaration

public static byte[] intToBytes(int val) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

    public static byte[] intToBytes(int val) {

        if (val == 0)
            return EMPTY_BYTE_ARRAY;

        int lenght = 0;

        int tmpVal = val;
        while (tmpVal != 0) {
            tmpVal = tmpVal >> 8;/* www .j  a v  a 2  s. co  m*/
            ++lenght;
        }

        byte[] result = new byte[lenght];

        int index = result.length - 1;
        while (val != 0) {

            result[index] = (byte) (val & 0xFF);
            val = val >> 8;
            index -= 1;
        }

        return result;
    }
}

Related

  1. intToBytes(int number, byte[] destination, int destinationIndex)
  2. intToBytes(int v)
  3. intToBytes(int v)
  4. intToBytes(int v, byte[] bytes)
  5. intToBytes(int v, final byte[] arr)
  6. intToBytes(int val, byte[] bytes, int start)
  7. intToBytes(int val, int byteCount)
  8. intToBytes(int value)
  9. intToBytes(int value)