PLEASE HELP with function to convert decimal to binary

Hi!

Can someone please explain to me what is the difference between the two functions below?
I created the function in the top and my friend created the function in the bottom. I just want to know why the function with the while loop prints the binary numbers backwards. And the recursive function prints the binary numbers correctly.

FYI I'm a noob.

Thank you in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

void findBinary(int num)
{
    int remainder = 0;

    while ( num > 0)
    {
        remainder = num % 2;
        cout << remainder;

        num = num / 2;
    }
    return;
}

******************************************
******************************************
******************************************

void findBinary(int num)
{
    int remainder = num;

    if  ( num > 0)
    {
        findBinary(num/2);
    }
    cout << remainder % 2;

    return;
}
Last edited on
The order you do things matters.

Both functions split values from the least-significant end of your number.

That's akin to reading the number 723 as 3, 2, 7.

The iterative function doesn't wait to write the digit it gets. So as soon as it gets that 3 it writes it, making it first in the output --> "327".

The recursive function waits until after the remaining digits are handled, and only then prints the number. Hence, the numbers come out in backwards order, which are correct: 7, 2, 3 --> "723".


You can fix the iterative version by storing the results in a string. Instead of couting the digit as soon as you get it, append it to a string. Once done, print the string backwards.

Hope this helps.
You are starting with the right most digit instead of the leftmost like recursion. Basically for example with 11 the binary is 1011 which is 8 + 2 + 1 with the while loop (yours) you check if its divisible by 2, 4, 8, 16...instead of 16, 8, 4, 2...

[edit] on a side note here is another version:
1
2
3
4
5
6
7
std::string decimalToBinary(int binary)
{
    if(binary == 0) return "0";
    if(binary == 1) return "1";
    if(binary & 1) return decimalToBinary(binary >> 1) + "1";
    return decimalToBinary(binary >> 1) + "0";
}
Last edited on
Here's my recursive version. :O)

1
2
3
4
std::string to_binary( unsigned n )
{
  return ((n > 1) ? to_binary( n / 2 ) : "") + "01"[ n & 1 ];
}

And generalized to radices in [2,36]:

1
2
3
4
5
6
7
8
std::string to_nary( unsigned n, unsigned radix )
{
  return ((n >= radix) ? to_nary( n / radix ) : "")
    + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[ n % radix ];
}

inline std::string to_binary ( unsigned n ) { return to_nary( n, 2 ); }
inline std::string to_klingon( unsigned n ) { return to_nary( n, 3 ); }
Topic archived. No new replies allowed.