gpt4 book ai didi

Java:将二进制转换为十六进制时出现 NumberFormatException

转载 作者:行者123 更新时间:2023-11-29 05:26:04 25 4
gpt4 key购买 nike

我有从 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 类型 - 结果是一样的。

如果你们能帮我更正这段代码,以便处理更大的数字,我将不胜感激。

最佳答案

在 Java 中,int 是一个带符号的 32 位,所以它的范围是

-2,147,483,648 to 2,147,483,647

所以你的值 10101010101010 超出了这个范围。

尝试使用更大的东西,比如 Long

long bin = Long.valueOf("10101010101010");
System.out.println(bin);

参见 Primitive Data Types

关于Java:将二进制转换为十六进制时出现 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22631431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com