,當我有功課從BIN轉換爲十六進制,我寫了下面的算法中的代碼:的Java:NumberFormatException的轉換二進制到十六進制
import java.util.Scanner;
public class BinaryToHex {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Binary number: ");
String b = input.next();
int bin = Integer.parseInt(b);
int arrlength = b.length();
while (arrlength%4 != 0){
arrlength++;
}
int[] arrbin = new int [arrlength];
int digit = 0;
String hex = "";
String str;
int conv;
for (int i = arrlength-1; i>=0; i--){
digit = bin%10;
arrbin[i]=digit;
bin = bin/10;
}
System.out.print("Hex value = ");
for (int index = 0; index < arrlength; index=index+4){
str = "" + arrbin[index] + "" + arrbin[index+1] + "" + arrbin[index+2] + "" + arrbin[index+3];
switch(str){
case "0000": str = "0"; break;
case "0001": str = "1"; break;
case "0010": str = "2"; break;
case "0011": str = "3"; break;
case "0100": str = "4"; break;
case "0101": str = "5"; break;
case "0110": str = "6"; break;
case "0111": str = "7"; break;
case "1000": str = "8"; break;
case "1001": str = "9"; break;
case "1010": str = "A"; break;
case "1011": str = "B"; break;
case "1100": str = "C"; break;
case "1101": str = "D"; break;
case "1110": str = "E"; break;
case "1111": str = "F"; break;
}
System.out.print(str);
}
}
}
的問題是,當我試圖把它轉換拋出更大的數字:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10101010101010"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at BinaryToHex.main(BinaryToHex.java:9)
我知道問題與int類型有關,但我無法弄清楚如何解決這個問題。我試圖使用長型 - 結果是一樣的。
我將不勝感激,如果你們,可以幫助我糾正這段代碼,以便使用更大的數字。
謝謝,它的作品!這就是我一直在尋找的東西!我後悔我不允許爲你投票......:| – Kirev