In network programming, long and int are usually processed in a native way rather than converting to string for bandwidth saving or encoding.
public class ByteOrderUtils {public static byte[] int2byte(int res) { byte[] targets = new byte[4]; targets[3] = (byte) (res & 0xff);// Lowest bit targets[2] = (byte) ((res >> 8) & 0xff);// Secondary low bit targets[1] = (byte) ((res >> 16) & 0xff);// Secondary high bit targets[0] = (byte) (res >>> 24);// Highest bit, unsigned right shift. return targets; }public static int byteArrayToInt(byte[] b){ byte[] a = new byte[4]; int i = a.length - 1,j = b.length - 1; for (; i >= 0 ; i--,j--) {//Start copy data from the tail of b (i.e. the low bit of int value) if(j >= 0) a[i] = b[j]; else a[i] = 0;//If b.length is less than 4, add 0 to the high bit } int v0 = (a[0] & 0xff) << 24;//&0xff converts the byte value to int to avoid the sign bits of the high bit after Java automatic type promotion, int v1 = (a[1] & 0xff) << 16; int v2 = (a[2] & 0xff) << 8; int v3 = (a[3] & 0xff) ; return v0 + v1 + v2 + v3; }public static byte[] long2byte(long res) { byte[] buffer = new byte[8]; for (int i = 0; i < 8; i++) { int offset = 64 - (i + 1) * 8; buffer[i] = (byte) ((res >> offset) & 0xff); }return buffer;}public static long byteArrayToLong(byte[] b){ long values = 0; for (int i = 0; i < 8; i++) { values <<= 8; values|= (b[i] & 0xff); } return values; }}The above is the full content of the java int conversion to byte and long conversion to byte brought to you by the editor. I hope everyone will support Wulin.com more~