Javaにおけるintとbyte配列の相互変換

8507 ワード

インプリメンテーションコード
package dream.kuber.test;

public class BytesUtil {
	public static int bytes2Int(byte[] bytes) {
		int result = 0;
		//   byte     int     
		result = bytes[0] & 0xff;
		result = result << 8 | bytes[1] & 0xff;
		result = result << 8 | bytes[2] & 0xff;
		result = result << 8 | bytes[3] & 0xff;
		return result;
	}
	
	public static byte[] int2Bytes(int num) {
		byte[] bytes = new byte[4];
		//      ,   8    , int   byte  
		bytes[0] = (byte)(num >>> 24);
		bytes[1] = (byte)(num >>> 16);
		bytes[2] = (byte)(num >>> 8);
		bytes[3] = (byte)num;
		return bytes;
	}
}


理解&0 xff
コードとコメントを参照:
package dream.kuber.test;

public class App {
	public static void main(String[] args) {
		//    8 ,00000000 00000000 00000000 10000000 -> 10000000,   10000000 -128
		byte b = (byte)128;
		//   -128
		System.out.println(b);
		// 10000000 -> 11111111 11111111 11111111 10000000,  i  -128
		int i = b;
		System.out.println(b); //   128, byte   ,   -128
		//     ,     byte 8  ,        0,       & 0xff   
		/**
		 *                            10000000
		 * 00000000 00000000 00000000 11111111     &  
		 * 
		 * 00000000 00000000 00000000 10000000   
		int j = b & 0xff; //      int  , byte   &   ,        
		System.out.println(j); //  128
	}
	
}