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...
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.
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: