我试着编写一个将二进制转换为十进制的代码。但它给了我一个巨大的成果。你能告诉我怎么做吗?我看到代码使用了余数并给出了正确的结果,但我真的很想知道代码中的错误是什么,谢谢
double number = 0;
for (int i = 0; i < 16; i++) {
double temp = str.charAt(16-1 - i) * Math.pow(2, i);
number = number + temp;
}
答案 0 :(得分:3)
以下是您的代码出错的地方:
str.charAt(16-1 - i) * Math.pow(2, i);
您只需将char
乘以double
。这将评估char
乘以双倍的ASCII值,而不是0或1。
您需要先将其转换为整数:
Integer.parseInt(Character.toString(str.charAt(16-1 - i))) * Math.pow(2, i)
或者,您可以:
Integer.parseInt(binaryString, 2)
答案 1 :(得分:1)
这里的人已经回答了什么问题。对字符执行Math.pow(2, i)
会产生不一致的结果。
如果您要将二进制值转换为Integer
,这可以帮助您。
Integer.parseInt(binaryString, 2)
值2
是radix
值。
Java documentation和类似的SO有关同一主题的讨论here。
答案 2 :(得分:0)
使用str.charAt(16-1-i)
时,会返回一个字母,代表一个字母。所以你不能得到数字0或1,而是相应的字母。由于字母在Java中表示为整数,因此您不会收到类型错误。代表0字母的数字是48,其中1代表49.要将字母转换为正确的数字,您必须写(str.charAt(16-1-i)-48)
而不是str.charAt(16-1-i)
。