gpt4 book ai didi

java - 从文件转换十六进制字符串的输出错误

转载 作者:行者123 更新时间:2023-11-30 03:14:57 25 4
gpt4 key购买 nike

我的代码输出有问题。我必须将十六进制字符串从文件转换为二进制,然后将该二进制转换为十进制。然后找到芯片中的RAM错误,我还没有编码。我现在主要担心的是,当我运行程序时,我的第一个结果是正确的,但对于其余 3 个十六进制到二进制输出,二进制字符串将自身附加到先前的二进制输出,并且它变成一个又长又错误的二进制字符串。

public static void main(String arg[]) throws IOException {
Scanner infile = new Scanner(new File("RAMerrors.txt"));

String result = "";
String binVal; // the binary value of the Hex

while (infile.hasNextLine()) {
String line = infile.nextLine();
Scanner input = new Scanner(line);
String hex = input.next();

for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);

switch (hexChar) {
case ('0'):
binVal = "0000";
break;
case ('1'):
binVal = "0001";
break;
case ('2'):
binVal = "0010";
break;
case ('3'):
binVal = "0011";
break;
case ('4'):
binVal = "0100";
break;
case ('5'):
binVal = "0101";
break;
case ('6'):
binVal = "0110";
break;
case ('7'):
binVal = "0111";
break;
case ('8'):
binVal = "1000";
break;
case ('9'):
binVal = "1001";
break;
case ('A'):
binVal = "1010";
break;
case ('B'):
binVal = "1011";
break;
case ('C'):
binVal = "1100";
break;
case ('D'):
binVal = "1101";
break;
case ('E'):
binVal = "1110";
break;
case ('F'):
binVal = "1111";
break;
default:
binVal = "invalid input";
break;
}
result += binVal;
}
System.out.println("Binary of " + hex + ":" + result);
System.out.println("And the decimal is " + convertBin2Dec(result) + "\n");
}
}

我的输出如下:

Binary of ABCDEFABC: 101010111100110111101111101010111100
And the decimal is 46118402748

Binary of 1A00D0000: 101010111100110111101111101010111100000110100000000011010000000000000000
And the decimal is 9223372036854775807

Binary of 7A0EDF301: 101010111100110111101111101010111100000110100000000011010000000000000000011110100000111011011111001100000001
And the decimal is 9223372036854775807

Binary of 3CDAEFFAD: 101010111100110111101111101010111100000110100000000011010000000000000000011110100000111011011111001100000001001111001101101011101111111110101101
And the decimal is 9223372036854775807

最佳答案

您没有在检查之间清除 result 变量。

如果您在 while 循环内声明 result,它应该可以解决您的问题。

关于java - 从文件转换十六进制字符串的输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32875100/

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