byte数组与int相互转换,在网络编程编解码中经常要用到类似的功能, 写了一个小工具。 使int与byte[]能相互转换
package chat;
/**
* @author is_zhoufeng
*/
public class ByteUtils {
/**
* byte数组转换为int
* @param bs 字节数组
* @param bigEnding 字节数组的顺序 是否使用高位在前的顺序
* @return
*/
public static int bytesToInt(byte[] bs , boolean bigEnding){
if(bs == null || bs.length != 4){
throw new RuntimeException("bs的长度必须为4位");
}
int i = 0 ;
if(bigEnding){
i |= (bs[0] & 0XFF) << 24 ;
i |= (bs[1] & 0XFFFF) >> 16 ;
i |= (bs[2] & 0XFFFFFF) >> 8 ;
i |= (bs[3] & 0XFFFFFFFF) ;
}else{
i |= (bs[3] & 0XFF) << 24 ;
i |= (bs[2] & 0XFFFF) >> 16 ;
i |= (bs[1] & 0XFFFFFF) >> 8 ;
i |= (bs[0] & 0XFFFFFFFF) ;
}
return i ;
}
/**
* int转换为byte数组
* @param i
* @param bigEnding 字节数组的顺序 是否使用高位在前的顺序
* @return
*/
public static byte[] intToBytes(int i , boolean bigEnding){
byte[] bs = new byte[4];
if(bigEnding){
bs[0] = (byte)(i >> 24) ;
bs[1] = (byte)(i >> 16) ;
bs[2] = (byte)(i >> 8) ;
bs[3] = (byte)(i) ;
}else{
bs[3] = (byte)(i >> 24) ;
bs[2] = (byte)(i >> 16) ;
bs[1] = (byte)(i >> 8) ;
bs[0] = (byte)(i) ;
}
return bs ;
}
public static void main(String[] args) {
byte[] bs = intToBytes(11 , true);
int i = bytesToInt(bs,true);
System.out.println(i);
bs = intToBytes(11 , false);
i = bytesToInt(bs,false);
System.out.println(i);
}
}