在 Java 中將十六進位字串轉換為整數
一、簡介
將十六進位 (Hex) 字串轉換為整數是程式設計期間的常見任務,特別是在處理使用十六進位表示法的資料類型時。
在本教程中,我們將深入研究在 Java 中將十六進位String
轉換為int
各種方法。
2. 理解十六進位表示
十六進位採用以 16 為基數,導致每個數字可以採用從 0 到 9 的 16 個可能值,後面接著(A)
到(F)
:
我們還要注意,在大多數情況下,十六進位字串以「 0x
」開頭表示其基數。
3.使用Integer.parseInt()
在 Java 中將十六進位字串轉換為整數的最簡單方法是透過Integer.parseInt()
方法。它將字串轉換為整數,並假定其寫入的基數。對我們來說,基數是 16:
@Test
public void givenValidHexString_whenUsingParseInt_thenExpectCorrectDecimalValue() {
String hexString = "0x00FF00";
int expectedDecimalValue = 65280;
int decimalValue = Integer.parseInt(hexString.substring(<span class="hljs-number">2</span>), 16);
assertEquals(expectedDecimalValue, decimalValue);
}
在上面的程式碼中,使用Integer.parseInt
將十六進位字串「 0x00FF00
」轉換為其對應的十進位值 65280,並且測試斷言結果與預期的十進位值相符。請注意,我們使用substring(2)
方法從hexString
中刪除「 ox
」部分。
4. 使用BigInteger
為了在處理非常大或無符號的十六進位值時獲得更大的靈活性,我們可以考慮使用BigInteger
。它對任意精度整數進行操作,因此可以在無數的上下文中使用。
以下是我們如何將十六進位字串轉換為BigInteger
,然後提取整數值:
@Test
public void givenValidHexString_whenUsingBigInteger_thenExpectCorrectDecimalValue() {
String hexString = "0x00FF00";
int expectedDecimalValue = 65280;
BigInteger bigIntegerValue = new BigInteger(hexString.substring(2), 16);
int decimalValue = bigIntegerValue.intValue();
assertEquals(expectedDecimalValue, decimalValue);
}
5.使用Integer.decode()
Integer.decode()
方法提供了將十六進位字串變更為整數的另一種方法。此方法處理十六進制和十進位字串。
在這裡,我們使用Integer.decode()
而不聲明基數,因為它是根據字串本身確定的:
@Test
public void givenValidHexString_whenUsingIntegerDecode_thenExpectCorrectDecimalValue() {
String hexString = "0x00FF00";
int expectedDecimalValue = 65280;
int decimalValue = Integer.decode(hexString);
assertEquals(expectedDecimalValue, decimalValue);
}
由於**Integer.decode()
方法可以處理字串中的「 0x
」前綴,因此我們不需要像前面的方法那樣使用substring(2)
手動刪除它。**
六,結論
總之,我們討論了十六進位表示的重要性,並深入研究了三種不同的方法:用於直接轉換的Integer.parseInt()
、用於處理大值或無符號值的BigInteger
以及用於處理十六進位和十進位字串的多功能性的Integer.decode()
,包括「 0x
」前綴。
與往常一樣,本文的完整程式碼範例可以在 GitHub 上找到。