【问题标题】:Java converting binary string to decimal [duplicate]Java将二进制字符串转换为十进制[重复]
【发布时间】:2018-06-05 18:26:43
【问题描述】:
我尝试编写将二进制转换为十进制的代码。但它给了我一个巨大的结果。你能告诉我怎么做吗?我看到了使用余数的代码并给出了正确的结果,但我真的想知道我的代码有什么问题,谢谢
double number = 0;
for (int i = 0; i < 16; i++) {
double temp = str.charAt(16-1 - i) * Math.pow(2, i);
number = number + temp;
}
【问题讨论】:
标签:
java
binary
decimal
converter
【解决方案1】:
这是您的代码出错的地方:
str.charAt(16-1 - i) * Math.pow(2, i);
您只是将char 乘以double。这将评估为 ASCII 值 char 乘以双精度数,而不是 0 或 1。
您需要先将其转换为整数:
Integer.parseInt(Character.toString(str.charAt(16-1 - i))) * Math.pow(2, i)
或者,您可以:
Integer.parseInt(binaryString, 2)
【解决方案2】:
这里的人已经回答了问题所在。对字符执行Math.pow(2, i) 会产生不一致的结果。
如果您要将二进制值转换为 Integer,这可能会对您有所帮助。
Integer.parseInt(binaryString, 2)
其中值2 是radix 值。
Java documentation 和类似的 SO 可以在 here 上讨论同一主题。
【解决方案3】:
当你使用str.charAt(16-1-i) 时,你会得到一个字符,它代表一个字母。所以你得到的不是数字 0 或 1,而是对应的字母。由于字母在 Java 中表示为整数,因此不会出现类型错误。表示 0 字母的数字是 48,1 是 49。要将字母转换为正确的数字,您必须写 (str.charAt(16-1-i)-48) 而不是 str.charAt(16-1-i)。