Writing a "for" loop to convert binary to decimal

I am using Brackets, and I need to write a for loop that converts a binary number into a decimal. The requirements are:

-Write a for loop that iterates from 0 to the end of the binary string (i.e "bin.length) just like when iterating through the arguments to a function (i.e arguments.length)
-multiply the value (0 or 1) at the current position in the string (i.e "bin[i]" if "i" is your counter variable) by 2 to the power of the string length minus the current position - 1
-when the loop is done, return the calculated value.

All I have so far is:

function binarytoDecimal (bin)

{

}
The instructions are your program; you only need to translate them to C++ syntax!

function binarytoDecimal (bin)

1
2
3
4
5
6
7
8
9
10
11
12
13
{
// You'll need to declare a variable to hold the 
result
while you're calculating, right?
// Now your instructions: // ( a for loop that iterates from 0; to the end of the binary string; ?? ) ( for i = 0; ; i <= somevalue ; ??) { multiply the value (0 or 1) at the current position in the string by 2 to the power of the string length minus the current position -1; } when the loop is done, return the calculated value }


Actually it could be more practical to calculate in high-to-low;
for (i = lengthofinput; i >0; i--)

this way you can use i as an index into your input directly . . .
Last edited on
Also, some additional hints are:

The value at each position in the binary number is equal to:
x*2^(length - i - 1)

where x is either a 0 or a 1 (the value at that position, e.g bin[i], "length" is the number of digits in the number, and "i" is the position of the number from left to right starting with 0
Topic archived. No new replies allowed.