Home  >  Article  >  类库下载  >  java int to byte and long to byte

java int to byte and long to byte

高洛峰
高洛峰Original
2016-10-08 13:40:232053browse

<br/>

In network programming, due to the need to save bandwidth or encoding, it is usually necessary to process long and int natively 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);// Second low bit
targets[1] = (byte) ((res >> 16) & 0xff);/ / Second highest 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--) {//Copy data starting from the tail of b (that is, the low bit of the int value)
if(j >= 0)
a[i] = b [j];
else
a[i] = 0;//If b.length is less than 4, fill the high bit with 0
}
int v0 = (a[0] & 0xff) c1fe1d106f8afa409a8fcb64d17ebf77> 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;
}

}

<br/>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn