Java中byte型別轉換為int型別
1. 概述
將byte
轉換為int
是一種常見操作,尤其是在處理低階資料操作、檔案 I/O 或網路通訊時。在本文中,我們將探討實現byte
到int
轉換的各種方法。
2. byte
和int
在 Java 中, byte
和int
是基本資料類型,在表示數值時具有不同的用途。 byte
是一種 8 位元有符號資料型,值範圍為 -128 到 127。int int
型態是 32 位元有符號整數,提供比 byte 更廣泛的範圍,從 -2 31到 2 31 -1 (-2,147,483,648至2,147,483,647) 。
3. 使用型別轉換
執行轉換的最直接、最常見的方法之一是將byte
變數簡單地型別轉換為int
變數:
class ByteToIntConversion {
static int usingTypeCasting(byte b) {
int i = b;
return i;
}
}
在此範例中,我們透過賦值直接將byte
轉換為int
變數。讓我們測試一下:
@Test
void givenByte_whenUsingTypeCasting_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingTypeCasting(b);
assertEquals(-51, result);
}
4.使用Integer.valueOf()
Integer
類別提供了從其他基本資料類型轉換值的便捷方法。我們可以使用它的靜態方法Integer.valueOf(),
它有助於將byte
轉換為int
:
static int usingIntegerValueOf(byte b){
return Integer.valueOf(b);
}
上面的程式碼範例採用一個byte
作為輸入,並將傳回指定byte
組值的Integer
實例。 Java 編譯器將自動套用拆箱,因為Integer
類別充當基本資料類型**int** .
我們可以執行測試來驗證其預期行為:
@Test
void givenByte_whenUsingIntegerValueOf_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingIntegerValueOf(b);
assertEquals(-51, result);
}
5. 使用Byte
組類
Byte
組類別是基本資料類型byte.
它提供了將byte
值作為物件使用的方法,包括用於處理byte
組值的轉換方法。
5.1.使用intValue()
Byte
類別提供了一種間接方法,透過其intValue()
方法將byte
轉換為int
資料型別。為了使這個方法有效,我們將原始值轉換為其物件表示,然後繼續轉換過程:
static int usingByteIntValue(byte b){
Byte byteObj = new Byte(b);
return byteObj.intValue();
}
在此範例中, intValue()
方法在執行擴展基元轉換後傳回一個int
值。讓我們測試一下:
@Test
void givenByte_whenUsingByteIntValue_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingByteIntValue(b);
assertEquals(-51, result);
}
5.2. Byte.toUnsignedInt()
從 Java 8 開始, Byte
類別提供了一個名為toUnsignedInt
實用方法,用於將byte
轉換為無integer.
此方法內部對位元組值與0xff
進行位元與運算:
static int usingByteUnsignedInt(byte b){
return Byte.toUnsignedInt(b);
}
值得注意的是,預設情況下,位元組到整數的轉換會保留值的符號。但是,上述方法將byte
值視為 unsigned byte
,從而產生等效的無integer
表示形式:
@Test
void givenByte_whenUsingByteUnsignedInt_thenConvertToInt() {
byte b = -51;
int result = ByteToIntConversion.usingByteUnsignedInt(b);
assertEquals(205, result);
}
六,結論
在本教程中,我們深入研究了將byte
轉換為int
資料類型的不同方法。每種方法都提供了執行轉換的可靠方法。選擇取決於為我們的特定用例選擇最合適的方法。
當處理負數並針對其有符號表示時,我們可以考慮使用型別轉換、 Integer.valueOf(),
或Byte
類intValue()
方法。或者,對於無符號轉換,我們可以選擇Byte.toUnsignedInt()
方法。
與往常一樣,完整的源代碼可以在 GitHub 上取得。