最近老有人問我int和byte的相互轉換,我當時表示好吃驚….項目中竟然會用到這兩者的轉換,o(╯□╰)o驚恐
雖然我目前還沒用到過,但還是總結下,供大家參考。
首先明確下定義,
byte 爲字節數據類型 ,有符號,佔1個字節,大小範圍爲-128~127
int爲整型類型,有符號型的,佔4個字節,大小範圍爲:-2147483648~2147483647
測試如下,
public static void main(String[] args) {
for(int i=-128; i<128; i++){
int tempInt = i;
byte tempByte = (byte)tempInt;
System.out.println(tempByte);
}
System.out.println("***********************");
for(int i=128; i<256; i++){
int tempInt = i;
byte tempByte = (byte)tempInt;
System.out.println(tempByte);
}
}
結果如下,
=>-128
-127
-126
-125
…(省略)
-1
0
1
2
…(省略)
126
127
“**************************”
-128
-127
-126
…(省略)
-4
-3
-2
-1
通過測試我們可以看到byte會在自己範圍內一直循環…,所以在轉的時候注意了,超出byte範圍會有位數的丟失哦。
PS,Integer有個byteValue方法可以直接獲得byte值…