In network programming, it is often necessary to process long and int in a native way, rather than to string, for bandwidth savings or coding purposes.
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);//Sub Low targets[1] = (byte)
(res >>) & 0xff);//secondary high 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--) {//from the tail of B (that is, the low of int value) Start copy data if (J >= 0) A[i] = B[j]; else A[i] = 0;//If b.length is less than 4, the high 0} int v0 = (a[0] & 0xff) << 24;//&0xff converts the byte value to an int without any difference, avoiding the Java automatic type elevation
Reserved high level sign bit 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 =-(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 small series for everyone to bring the Java int to byte and long to byte of the whole content of the method, I hope that we support cloud-Habitat Community ~