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!

 ``12345678910111213141516171819202122`` `````` #include using namespace std; int hi (int x) { return x%2; } int main () { int x; cout<<"Enter number: "; cin>>x; while(x!=0) { cout<
Last edited on
 ``123456789101112131415`` ``````#include 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

 ``123456789101112131415161718192021`` ``````#include 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.