In network programming, in order to conserve bandwidth or coding needs, it is often necessary to process long and int in the native way, instead of converting to string.
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--) {//Start copy data from the tail of B (that is, the low of the int value)
if (J >= 0)
A[i] = B[j];
Else
A[i] = 0;//If b.length is less than 4, the high will be 0
}
int v0 = (a[0] & 0xff) << 24;//&0xff converts the byte value to int, avoids the high sign bit after the 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 =-(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;
}
}
java int to byte and long to byte