Converting Binary to Decimal in Java [duplicate]

佐手、 提交于 2020-01-26 04:17:12

问题


I'm almost done with implementing a code that allows the user to input a decimal number into binary and then have the binary number reversed and then converted back to decimal.

I solved everything except for the Binary to decimal part. It keeps giving me the same number over and over again no matter what I type. I don't understand why. Basically, why is the last part of my code wrong? I'm having trouble with finding the length of the array/string and then have it multiply by 2^n etc...


回答1:


There are two issues in this code.

1) You didn't store the result of decimal-to-binary convertation. You should introduce new String variable to store string with reversed binary value.

2) Your binary-to-decimal algorithm is incorrect. s.charAt(i) returns char value but you need double value to use it in calculation. Math.pow(2, (s.length() - i - 1)) is also incorrect - as I understand it's for non-reversed binary values.

Fixed version of code should looks like:

public static void main(String[] args) {
    int a[] = {0, 1};

    int number;
    int remainder;
    String binary = "";

    Scanner in = new Scanner(System.in);

    System.out.print("Enter Decimal Number: ");
    number = Integer.parseInt( in.next());

    System.out.print("Binary Number in Reverse: ");
    do {
        remainder=number%2;
        if(remainder > 0){
            binary += a[1];
            //System.out.print(a[1]);
        }
        else{
            binary += a[0];
            //System.out.print(a[0]);
        }
        number=number / 2;
    } while(number>0);

    System.out.print(binary);

    System.out.print(" \nDecimal number: ");
    //String s = Integer.toString(number);
    double result = 0;
    for (int i = 0; i < binary.length(); i++)
       result = result + Double.parseDouble(binary.substring(i, i + 1)) * Math.pow(2, i);
    System.out.print(result);
}



回答2:


number will always be zero or less according to your do-while loop condition: while(number>0);

this causes your variable s (please pick better variable names...) to always be "0".

i think you can figure out the rest.



来源:https://stackoverflow.com/questions/14790568/converting-binary-to-decimal-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!