我有从BIN转换为HEX的作业,我写了以下算法代码:
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类型有关,但我无法弄清楚如何解决这个问题。我尝试使用long类型 - 结果是一样的。
如果你们能帮助我纠正这些代码,为了使用更大的数字,我将不胜感激。
答案 0 :(得分:3)
在Java中,int是带符号的32位,因此其范围是
-2,147,483,648 to 2,147,483,647
所以你的10101010101010的价值超出了这个范围。
尝试使用像Long一样大的东西
long bin = Long.valueOf("10101010101010");
System.out.println(bin);
答案 1 :(得分:0)
我做得很快又脏。应该适用于所有长度:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Binary number: ");
String b = input.next();
while (b.length() % 4 != 0) b = "0" + b;
StringBuilder builder = new StringBuilder();
for (int count = 0; count < b.length(); count += 4) {
String nibble = b.substring(count, count + 4);
builder.append(Integer.toHexString(Integer.parseInt(nibble, 2)));
}
System.out.println(builder);
}
答案 2 :(得分:0)
这个数字确实太大了。如果您需要这么大的数字,请使用Long.parseLong()
和long
类型而不是int
。
编辑:
我刚才明白你实际上想要解析二进制号码。所以,使用Integer.parseInt(str, 2)
。否则,该数字被解释为十进制。
答案 3 :(得分:0)
我用这种方法进行转换
public static String binaryToHex(String bin) {
return String.format("%21X", Long.parseLong(bin,2)) ;
}
答案 4 :(得分:0)
如果输入String的最大值为32位,则无需使用Long。
-- for any binary input till 32 bit lenght following will work
Integer.parseInt(yourBinaryString, 2)
-- for any binary input till 64 bit lenght following will work
Long.parseLong(yourBinaryString, 2)
-- for longer binary string input values have a look at BigInteger