首页  >  文章  >  类库下载  >  java int转byte和long转byte

java int转byte和long转byte

高洛峰
高洛峰原创
2016-10-08 13:40:232054浏览

<br/>

在网络编程中,出于节约带宽或者编码的需要,通常需要以原生方式处理long和int,而不是转换为string。

public class ByteOrderUtils {

public static byte[] int2byte(int res) { 
byte[] targets = new byte[4]; 

targets[3] = (byte) (res & 0xff);// 最低位 
targets[2] = (byte) ((res >> 8) & 0xff);// 次低位 
targets[1] = (byte) ((res >> 16) & 0xff);// 次高位 
targets[0] = (byte) (res >>> 24);// 最高位,无符号右移。 
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--) {//从b的尾部(即int值的低位)开始copy数据 
if(j >= 0) 
a[i] = b[j]; 
else 
a[i] = 0;//如果b.length不足4,则将高位补0 

int v0 = (a[0] & 0xff) int v1 = (a[1] & 0xff) int v2 = (a[2] & 0xff) 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 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 values } 
return values; 
}

}

<br/>


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn