如下是代碼,請教一下兩個方法體中的每句代碼是什么意思,謝謝了。public class ByteTrans { public static byte[] intToBytes(int id) { byte [] arr = new byte[4]; arr[0] = (byte)((int)(id >> 0 * 8) & 0xff); arr[1] = (byte)((int)(id >> 1 * 8) & 0xff); arr[2] = (byte)((int)(id >> 2 * 8) & 0xff); arr[3] = (byte)((int)(id >> 3 * 8) & 0xff); return arr; } public static int byteToInt(byte[] arr) { int rs0 = (int)((arr[0] & 0xff) << 0 * 8); int rs1 = (int)((arr[1] & 0xff) << 1 * 8); int rs2 = (int)((arr[2] & 0xff) << 2 * 8); int rs3 = (int)((arr[3] & 0xff) << 3 * 8); return rs0 + rs1 + rs2 + rs3; } public static void main(String [] args) { byte [] arr = intToBytes(8143); for(byte b : arr) { System.out.print(b + " "); } System.out.println("\n" + byteToInt(arr)); }}
1 回答

OuBa
TA貢獻6條經驗 獲得超5個贊
這個主要一個位運算的知識點.首先你要知道一個int?是占4個字節的(32位)。而一個byte占一個字節(8位) 舉個例子 比如一個十進制整數?23?如果是int存儲的話,在計算機中是這樣的 0000?0000?0000?0000?0000?0000?0001?0111?????------->??1+2+4+16??=?23 如果是byte存儲的話,在計算機中是這樣的 0001?0111?----->?1+2+4+16.(唯一的區別,int占的空間大可以存儲更大的數,byte則最大智能存儲255?2的8次方減1) 所以你將整形轉發為字節數組,就需要用4個byte來存儲。 通過每次的移位與&運算以此將4個字節的int轉換為1個字節的byte。。。 byte轉換int也是如此原理。去理解一些位操作你就懂了
添加回答
舉報
0/150
提交
取消