byte與int的區別:
- byte uses 1 byte while int uses 4 bytes.
- integer literals like "45" are of int not byte.If you want a literal to be a byte, you have to cast it: "(byte)45".
- When values are promoted as part of an expression or as parameters to a method call, they may be promoted to int, but never to byte.
- Many parts of the Java language used int, but none of them use byte. For example, the length of an array is an int.
byte類型的使用場合:
由于不同的機器對于多字節數據(int 就是采用4個byte保存數據)的存儲方式不同,可能是 低字節向高字節存儲,也可能是從高字節向低字節存儲,這樣,在 分析網絡協議或文件格時,為了解決不同機器上的字節存儲順序問題,用byte類型來表示數據是合適的。而通常情況下,由于其表示的數據范圍很小,容易造成溢出,應避免使用。
/**
* Convert an int to a byte array
*
* @param value int
* @return byte[]
*/
public static byte[] intToByteArray(int value) {
byte[] b = new byte[4];
// 使用4個byte表示int
for (int i = 0; i < 4; i++) {
int offset = (b.length - 1 - i) * 8; // 偏移量
b[i] = (byte) ((value >> offset) & 0xFF); //每次取8bit
}
return b;
}
/**
* Convert the byte array to an int starting from the given offset.
*
* @param b The byte array
* @param offset The array offset,如果byte數組長度就是4,則該值為0
* @return The integer
*/
public static int byteArrayToInt(byte[] b, int offset) {
int value = 0;
for (int i = 0; i < b.length; i++) {
int shift = (b.length - 1 - i) * 8;
value += (b[i + offset] & 0xFF) << shift;
}
return value;
}
public static void main(String[] args) {
byte[] bb=intToByteArray(255);
for(int i=0;i<bb.length;i++){
System.out.println(bb[i]);
}
}
輸出結果:
0
0
0
-1
這是補碼的形式(10000001),取反加1可以得到源碼(11111111)