converting to decimal but without using integer.parseInt() method

sara james

Greenhorn

Posts: 13

posted 2 years ago

hello guys!
so this is my first programming course and i have an assignment to convert a binary number entered by the user to a decimal. and my binary number should be stored in a a string.
and to check that all my digits are 1s and 0s i need to use a method to make sure it's valid and return true if the the number is correct and false otherwise.
so i did a search and saw that everyone was using the integer.parseInt(String , int radix) method to convert a binary string to int which worked completely fine, however, the only problem is we didn't take this with my professor so I'm not sure if it's OK and that maybe he wants another way to convert ? so my question is: how can i write this code in another way that doesn't use this method?.
here's my code:

this is my output:

enter a binary number to convert to decimal:
110101
the equivalent decimal value is: 53

sara james wrote: i understand that the right most digit has the value 2^0 so working my way to the left it would be: 110101 and taking the 1s only:
53 = 2^5 + 2^4 + 2^3 + 2^0

but i don't know how to write that in java ??

You can do it with a loop, that is very similar to the one in the validBinary() method. Of course, you have a bit of math to do -- which will require calculating based on the index of the loop. I recommend working it out on paper first, as it will be much easier to envision when you draw it out.

If you iterate the String from right to left, I think the arithmetic becomes quite straightforward.

Stephan van Hulst

Saloon Keeper

Posts: 7987

143

posted 2 years ago

In my opinion, it's easier to start with the leftmost non-zero bit in the string, and multiply an accumulator by two after adding the value of the bit to it, for each remaining bit.

The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.

Campbell Ritchie

Marshal

Posts: 56546

172

posted 2 years ago

That sounds easy too. You probably don't need to look for non‑zero bits; it is probably easier to add 0 a few times if there are leading 0s.
You would need to convert from numbers in the String to bits, and one way to do it is to remember that a char is not a letter but a number and you can subtract two chars.