Converting base 10 to base 2

I have a code to convert base 10 to base 2 but it spits the binary number out backwards. For example putting in 4, my program will return 001 instead of 100

#include <stdio.h>
#include <string.h>
#include <malloc.h>

#include <iostream>


using namespace std;

void show_binary(int u)
{
cout << "Enter number to convert to base 2" << endl;

cin >> u;

while(u > 1)
{
if((u % 2) == 0)
{
cout << "0";
}
else
{
cout << "1";
}

u = u >> 1;
}

cout << "1" << endl;

}


int main(int argv, char *argv[])
{

int number = 132;
show_binary(number);

return 0;
}

if anyone can tell me what i did wrong that would be great!
Last edited on
Simply store it in a string, appending the characters at the front.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void show_binary( int dec )
{
    std::cout << "decimal = " << dec << "\n";
    
    std::string bin{};
    
    while( dec > 0 ) {
        if( dec % 2 == 0 ) bin.insert( bin.begin( ), '0' );
        else bin.insert( bin.begin( ), '1' );
        
        dec >>= 1;
    }
    
    std::cout << "binary = " << bin << "\n";
}


decimal = 24
binary = 11000
Last edited on
Or put all the binary digits in a vector<int> (one-by-one, using push_back() ) and write them out in reverse order: see
http://www.cplusplus.com/reference/vector/vector/push_back/

or put the binary digits in a list<int> (one-by-one, using push_front() ) and write them out in forward order: see
http://www.cplusplus.com/reference/list/list/push_front/


Thank You!!
Topic archived. No new replies allowed.