Converting Binary to Decimal in Java -
this question has reply here:
converting decimal binary java 20 answersi'm done implementing code allows user input decimal number binary , have binary number reversed , converted decimal.
i solved except binary decimal part. keeps giving me same number on , on 1 time again no matter type. don't understand why. basically, why lastly part of code wrong? i'm having problem finding length of array/string , have multiply 2^n etc...
there 2 issues in code.
1) didn't store result of decimal-to-binary convertation. should introduce new string variable store string reversed binary value.
2) binary-to-decimal algorithm incorrect. s.charat(i) returns char value need double value utilize in calculation. math.pow(2, (s.length() - - 1)) wrong - understand it's 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: "); { 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; (int = 0; < binary.length(); i++) result = result + double.parsedouble(binary.substring(i, + 1)) * math.pow(2, i); system.out.print(result); }
java binary decimal
No comments:
Post a Comment