Here you can find the source of int2Bytes(int num)
public static byte[] int2Bytes(int num)
//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; } }