java Int數據工具類
阿新 • • 發佈:2017-11-01
byte ++ res data 字節數組 pub urn 轉換成 ava
1、在使用tcp協議傳輸數據時,使用到的 Int 數據的工具類方法
//將 Int 數據轉換成字節數組
public static byte[] intToByteArray(int data){
byte[] result = new byte[4];
result[0] = (byte)((data >> 24) & 0xFF);
result[1] = (byte)((data >> 16) & 0xFF);
result[2] = (byte)((data >> 8) & 0xFF);
result[3] = (byte)(data & 0xFF);
return result;
}
//將4個字節的字節數組轉換成 Int 數據
public static int byteArrayToInt(byte[] bytes){
int value = 0;
for(int i = 0; i < 4; i++){
value += (bytes[i] & 0xFF) << (8*(3-i));
}
return value;
}
java Int數據工具類