byte数组与int相互转换

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);  
	}
	
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值