Java 将二进制字符串转换为十进制

Java converting binary string to decimal

我试图编写一个将二进制转换为十进制的代码。但它给了我一个巨大的结果。你能告诉我怎么做吗?我看到使用余数的代码并给出了正确的结果,但我真的想知道我的代码中有什么错误,谢谢

    double number = 0;
    for (int i = 0; i < 16; i++) {
        double temp = str.charAt(16-1 - i) * Math.pow(2, i);
        number = number + temp;
    }

这是您的代码出错的地方:

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 这可以帮助您。

Integer.parseInt(binaryString, 2)

其中值 2radix 值。

Java documentation and similar SO Discussion on the same topic is available here.