Java Integer to Byte Array int2Bytes(int num)

Here you can find the source of int2Bytes(int num)

Description

Convert int to bytes, for small integer, only low-digits are stored in bytes, and all high zero digits are removed to save memory.

License

Open Source License

Declaration

public static byte[] int2Bytes(int num) 

Method Source Code

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

public class Main {
    /**/*ww  w .j a v a  2  s  .  c  om*/
     * Convert int to bytes, for small integer, only low-digits are stored in
     * bytes, and all high zero digits are removed to save memory. For example:
     * number 1 should convert to one byte [00000001], number 130
     * should convert to two bytes [00000001, 00000010]
     * @return
     */
    public static byte[] int2Bytes(int num) {
        byte[] buffer = new byte[4];
        for (int ix = 0; ix < 4; ++ix) {
            int offset = 32 - (ix + 1) * 8;
            buffer[ix] = (byte) ((num >> offset) & 0xff);
        }

        int i = 0;
        for (i = 0; i < buffer.length - 1; i++) {
            byte b = buffer[i];
            if (b != 0) {
                break;
            }
        }

        //remove zero high bytes
        byte[] buffer2 = new byte[4 - i];
        for (int j = 0; j < buffer2.length; j++) {
            buffer2[j] = buffer[i + j];
        }
        return buffer2;
    }
}

Related

  1. int2Bytes(int i, byte[] bytes, int offset)
  2. int2bytes(int integer)
  3. int2bytes(int intValue)
  4. int2Bytes(int l, byte[] target, int offset)
  5. int2Bytes(int n, byte[] dst, int start)
  6. int2bytes(int num)
  7. int2Bytes(int num)
  8. int2bytes(int num)
  9. int2bytes(int num, int len)