您的位置:首页 > 其它

整型int和字节数组byte相互转换

2011-01-27 10:40 525 查看
public class Test {
	   public static void main(String args[] ) {
	        int i = 212123;
	        byte[] b = toByteArray(i, 4);   //整型到字节,
	       System.out.println( "212123 bin: " + Integer.toBinaryString(212123));//212123的二进制表示
	       System.out.println( "212123 hex: " + Integer.toHexString(212123));  //212123的十六进制表示  
	        for(int j=0;j<4;j++){
	              System.out.println("b["+j+"]="+b[j]);//从低位到高位输出,java的byte范围是-128到127
	        }
	       
	        int k=toInt(b);//字节到整型,转换回来
	        System.out.println("byte to int:"+k); 
	      
	    }
	    
	    // 将iSource转为长度为iArrayLen的byte数组,字节数组的低位是整型的低字节位
	    public static byte[] toByteArray(int iSource, int iArrayLen) {
	        byte[] bLocalArr = new byte[iArrayLen];
	        for ( int i = 0; (i < 4) && (i < iArrayLen); i++) {
	            bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );
	          
	        }
	        return bLocalArr;
	    }   
	     // 将byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位
	    public static int toInt(byte[] bRefArr) {
	        int iOutcome = 0;
	        byte bLoop;
	        
	        for ( int i =0; i<4 ; i++) {
	            bLoop = bRefArr[i];
	            iOutcome+= (bLoop & 0xFF) << (8 * i);
	          
	        }  
	        
	        return iOutcome;
	    }    
}




输出:
212123 bin: 110011110010011011
212123 hex: 33c9b
b[0]=-101
b[1]=60
b[2]=3
b[3]=0
byte to int:212123

注:
上面的toInt()也可以这样定义



public static int toInt(byte[] bRefArr) {
    int iOutcome = 0;
    byte bLoop;
    for ( int i =0; i<4 ; i++) {
	bLoop = bRefArr[i];
	iOutcome = iOutcome | (bLoop & 0xFF) << (8 * i);          
    }  
    return iOutcome;
}




本文转自:http://snowlotus.javaeye.com/blog/246512
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: