This question already has an answer here:
-
Converting Decimal to Binary Java
28 answers
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...
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);
}
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.