Java将二进制字符串转换为十进制
我试着写一个将二进制转换成十进制的代码。但它给了我一个巨大的结果。你能告诉我怎么做吗。我看到代码使用了余数并给出了正确的结果,但我真的很想知道我的代码中有什么错误,谢谢Java将二进制字符串转换为十进制,java,binary,decimal,converter,Java,Binary,Decimal,Converter,我试着写一个将二进制转换成十进制的代码。但它给了我一个巨大的结果。你能告诉我怎么做吗。我看到代码使用了余数并给出了正确的结果,但我真的很想知道我的代码中有什么错误,谢谢 double number = 0; for (int i = 0; i < 16; i++) { double temp = str.charAt(16-1 - i) * Math.pow(2, i); number = number + temp; } doub
double number = 0;
for (int i = 0; i < 16; i++) {
double temp = str.charAt(16-1 - i) * Math.pow(2, i);
number = number + temp;
}
double number=0;
对于(int i=0;i<16;i++){
双温=str.charAt(16-1-i)*数学功率(2,i);
数字=数字+温度;
}
以下是您的代码出错的地方:
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)
当您使用str.charAt(16-1-i)时,返回一个字符,它表示一个字母。所以你不会得到数字0或1,而是相应的字母。由于字母在Java中表示为整数,所以不会出现类型错误。代表0字母的数字是48,代表1的数字是49。要将字母转换为正确的数字,您必须编写
(str.charAt(16-1-i)-48)
,而不是str.charAt(16-1-i)
这里的人已经回答了问题所在。对字符执行Math.pow(2,i)
会产生不一致的结果
如果要将二进制值转换为整数
,这可能会对您有所帮助
Integer.parseInt(binaryString, 2)
其中,值2
是基数
值
因此,可以就同一主题进行讨论