Binary conversion with recursion

Hello, I was trying the binary to decimal conversion with recursion and the diff between that and the octal to decimal one too and the only difference was 1 number (8 or 2)

1
2
3
4
5
long btod(long n){
if(n == 0) return 0;

return n%10 + (2*btod(n/10));
}


Literally changing line 4 to:
return n%10 + (8*btod(n/10));

Makes the diff, tracing it gets me the results but the reason behind it is.. ? Is it cause 2^0, 2^1,... for binary and 8^0, 8^1,... for octal ? I mean that could be the reason but I still don't know why we multiply either of them by the function call.
If the question isn't clear, it's fine if someone criticizes that rather than ignore it :P
The formula behind it is this:

sum(digitn * basen) where n = 0 ... number size - 1

What you have to do is separating the digit (n%10) and multiplying the base with it self as many times as its position within the number and multiplying this with the digit.
1
2
3
4
5
6
7
8
9
10
11
long binaryToDecimal(long n) {
 int remainder;
    long decimal = 0, i=0;
    while(n != 0) {
        remainder = n%10;
        n = n/10;
        decimal = decimal + (remainder*pow(2,i));
        ++i;
    }
    return decimal;
}


between this and the recursive function, where is this part:
(remainder*pow(2,i)); cause idk if there is anything equivalent to squaring but multiplying by the number x times, but maybe I am not aware of a special thing here
Well, in each recursion there is an add and multiply as long as digits are available.

So for instance after 4 recursion you get something like this:

return n0%10 + n1%10 + n2%10 + n3%10 + (8*8*8*btod(n/10));

Notice that the first recursion is called directly and hence does not have a multiplyer.

In a loop it would look like this:
1
2
3
4
5
6
7
8
9
long binaryToDecimal(long n) {
    long decimal = n%10, base0 = 2, base = base0;
    while(n != 0) {
        n /= 10;
        decimal += (n%10 * base);
        base *= base0;
    }
    return decimal;
}
Topic archived. No new replies allowed.