Oct 17, 2016 at 9:50pm UTC
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 Oct 17, 2016 at 9:51pm UTC
Oct 17, 2016 at 11:37pm UTC
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 Oct 17, 2016 at 11:39pm UTC