<br/>
在网络编程中,出于节约带宽或者编码的需要,通常需要以原生方式处理long和int,而不是转换为string。
public class ByteOrderUtils {
public static byte[] int2byte(int res) { <br/>byte[] targets = new byte[4]; <br/><br/>targets[3] = (byte) (res & 0xff);// 最低位 <br/>targets[2] = (byte) ((res >> 8) & 0xff);// 次低位 <br/>targets[1] = (byte) ((res >> 16) & 0xff);// 次高位 <br/>targets[0] = (byte) (res >>> 24);// 最高位,无符号右移。 <br/>return targets; <br/>}
public static int byteArrayToInt(byte[] b){ <br/>byte[] a = new byte[4]; <br/>int i = a.length - 1,j = b.length - 1; <br/>for (; i >= 0 ; i--,j--) {//从b的尾部(即int值的低位)开始copy数据 <br/>if(j >= 0) <br/>a[i] = b[j]; <br/>else <br/>a[i] = 0;//如果b.length不足4,则将高位补0 <br/>} <br/>int v0 = (a[0] & 0xff) << 24;//&0xff将byte值无差异转成int,避免Java自动类型提升后,会保留高位的符号位 <br/>int v1 = (a[1] & 0xff) << 16; <br/>int v2 = (a[2] & 0xff) << 8; <br/>int v3 = (a[3] & 0xff) ; <br/>return v0 + v1 + v2 + v3; <br/>}<br/><br/>public static byte[] long2byte(long res) { <br/>byte[] buffer = new byte[8]; <br/>for (int i = 0; i < 8; i++) { <br/>int offset = 64 - (i + 1) * 8; <br/>buffer[i] = (byte) ((res >> offset) & 0xff); <br/>}<br/>return buffer;<br/>}
public static long byteArrayToLong(byte[] b){ <br/>long values = 0; <br/>for (int i = 0; i < 8; i++) { <br/>values <<= 8; values|= (b[i] & 0xff); <br/>} <br/>return values; <br/>}
}
<br/>