10
I'm working on this program that takes a binary string and converts it to decimal, using this guide to convert from binary to decimal. When I run through the for loop in my head, I get what the correct outputs would be. And yet, when I run my program, I get this strange output:
1
3
7
15
31
63
127
The actual output should look like this:
1
2
5
11
22
44
89
I cannot figure this out for the life of me. Why is my program doing this? Here's the current source code:
public class BinaryToDecimal
{
public static void main(String[] args)
{
String binary = "1011001";
int toMultiplyBy;
int decimalValue = 0;
for (int i = 1; i <= binary.length(); i++)
{
int whatNumber = binary.indexOf(i);
if (whatNumber == 0)
{
toMultiplyBy = 0;
}
else
{
toMultiplyBy = 1;
}
decimalValue = ((decimalValue * 2) + toMultiplyBy);
System.out.println(decimalValue);
}
}
}