Java int to byte and long to byte, intbyte
In network programming, to save bandwidth or coding, you usually need to process long and int in native mode instead of converting to string.
Public class ByteOrderUtils {
Public static byte [] int2byte (int res ){
Byte [] targets = new byte [4];
Targets [3] = (byte) (res & 0xff); // second bit
Targets [2] = (byte) (res> 8) & 0xff); // low position
Targets [1] = (byte) (res> 16) & 0xff); // high
Targets [0] = (byte) (res >>> 24); // highest bit, unsigned shifted to the right.
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 --) {// copy data from the end of B (that is, the low position of the int value)
If (j> = 0)
A [I] = B [j];
Else
A [I] = 0; // If B. length is less than 4, the high value is 0.
}
Int v0 = (a [0] & 0xff) <24; // & 0xff converts the byte value to an int value without any difference. This prevents the high sign bit from being retained after the Java automatic type upgrade.
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;
}
}