Binary Numbers Not showed in correct order


I wrote a program that outputs the binary number of a decimal number passed to it, however the binary number is out putted backwards. So the binary of 25 is 11001 but my program gives 10011. Can any one help me? Thanks in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  #include <iostream>
using namespace std;

int hi (int x)
{
	return x%2;	
}

int main ()
{
	int x;

	cout<<"Enter number: ";
	cin>>x;

	while(x!=0)
	{
		cout<<hi(x); //25 binary = 11001
		x=x/2;
	}
	return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

void hi( unsigned int x )
{
    const int last_digit = x % 2 ; // hold the rightmost digit
    if( x > 1 ) hi( x/2 ) ; // first print the binary digits to the left
    std::cout << last_digit ; // and then print the rightmost digit
}

int main()
{
    const unsigned int n = 25 ;
    hi(n) ; // prints 11001
    std::cout << '\n' ;
}
I think it will be better to write a recursive function. For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

void DecToBinaryOutput( unsigned int x )
{
   unsigned int bit = x % 2;
   x /= 2;
   if ( x ) DecToBinaryOutput( x );
   std::cout << bit;
}

int main()
{
   std::cout << "Enter a non-negative number: ";

   unsigned int x = 0;
   std::cin >> x;

   DecToBinaryOutput( x );

   std::cout << std::endl;
}
Last edited on
Topic archived. No new replies allowed.