2012-03-12 144 views
2

我想轉換爲像這樣的int,但我得到一個異常。java轉換爲int

String strHexNumber = "0x1"; 
    int decimalNumber = Integer.parseInt(strHexNumber, 16); 
    Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1" 
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) 
at java.lang.Integer.parseInt(Integer.java:458) 

如果有人能解決它,這將是一個很大的幫助。

謝謝。

回答

4

當然 - 你需要擺脫「0X」的一部分,如果你想使用parseInt

int parsed = Integer.parseInt("100", 16); 
System.out.println(parsed); // 256 

如果您知道你的價值將啓動「0X」你可以使用:

String prefixStripped = hexNumber.substring(2); 

否則,它只是測試:

number = number.startsWith("0x") ? number.substring(2) : number; 

請注意,您應該考慮負數如何表示。

編輯:亞當的解決方案使用decode肯定會起作用,但是如果你已經知道基數,那麼IMO就明確地陳述它,而不是推斷它 - 特別是如果它讓人們感到驚訝,將「035」視爲八進制, 例如。當然,每種方法都適用於不同的時間,因此值得了解兩者。選擇最清楚,最清晰地處理您特定情況的人。

+1

沒必要。看我的解決方案。 – Adam 2012-03-12 16:23:57

+1

@亞當:看我的編輯。 – 2012-03-12 16:36:53

1

Integer.parseInt只能解析格式化爲像int一樣的字符串。所以你可以解析「0」或「12343」或「-56」而不是「0x1」。

0

在你要求Integer類解析它之前,你需要從字符串的前面去掉0xparseInt方法期望傳入的字符串只是指定基數的數字/字母。

4

這是因爲0x前綴是不允許的。這只是一個Java語言的東西。

String strHexNumber = "F777"; 
int decimalNumber = Integer.parseInt(strHexNumber, 16); 
System.out.println(decimalNumber); 

如果你想與解析0x開頭,然後使用整型,龍等可用.decode方法串

int value = Integer.decode("0x12AF"); 
System.out.println(value); 
0

在這裏嘗試使用此代碼: -

import java.io.*; 
import java.lang.*; 

public class HexaToInteger{ 

    public static void main(String[] args) throws IOException{ 

    BufferedReader read = 

    new BufferedReader(new InputStreamReader(System.in)); 

    System.out.println("Enter the hexadecimal value:!"); 

    String s = read.readLine(); 

    int i = Integer.valueOf(s, 16).intValue(); 

    System.out.println("Integer:=" + i); 

    } 

} 
+0

Integer.valueOf(「0x1」,16)拋出一個NumberFormatException ... – Adam 2012-03-12 16:25:46

+0

那麼數字格式是錯誤的,cuz java不識別他的0x1數字。 – engma 2012-03-12 16:27:57

+0

被問到的問題是如何轉換字符串與0x前綴...不是沒有... – Adam 2012-03-12 16:31:02

0

是的,Integer仍然期待某種字符串的數字。 x真的會搞砸了。

0

根據六角形的大小,您可能需要使用一個BigInteger(你大概可以跳過「L」檢查,並在你的修剪;-)):

 // Convert HEX to decimal 
     if (category.startsWith("0X") && category.endsWith("L")) { 
      category = new BigInteger(category.substring(2, category.length() - 1), 16).toString(); 
     } else if (category.startsWith("0X")) { 
      category = new BigInteger(category.substring(2, category.length()), 16).toString(); 
     }