number to binary in c++

Hi there!

I'm new to programming, so I hope this won't be a stupid question.

I was trying to create a program that would convert simple numbers to binary code, so, for example, 128 would be 10000000.

this is what I've made so far:

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
33
34
35
36
37
38
39
 #include <iostream>


using namespace std;
int x1;
int x2;
int x3;
int x4;
int x5;
int x6;
int x7;
int x8;

int main()
{
    //128 64 32 16 8 4 2 1
    int a;
    cin>> a;
    cout<< endl;

    if(a<=128){x1=0;}
    else if (a>=128){x1=1; a=a-128;}
    if (a<=64){x2=0;}
    else if (a>=64){x2=1; a=a-64;}
    if(a<=32){x3=0;}
    else if (a>=32){x3=1; a=a-32;}
    if(a<=64){x4=0;}
    else if (a>=16){x4=1; a=a-16;}
    if(a<=8){x5=0;}
    else if (a>=8){x5=1; a=a-8;}
    if(a<=4){x6=0;}
    else if (a>=4){x6=1; a=a-4;}
    if(a<=2){x7=0;}
    else if (a>=2){x7=1; a=a-2;}
    if(a<=1){x8=0;}
    else if (a>=1){x8=1; a=a-1;}
    cout<< x1 << x2 << x3 << x4<< x5 << x6 << x7 << x8 << endl;

}

It doesn't seem to work at all, it gives the wrong answers. For example, when I type in 78, it gives 01001101, which is wrong. (78 in binary is 1001110)
Last edited on
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
33
34
35
36
37
38
39
40
41

#include <iostream>
using namespace std;

int a;
void convertbinary(int n)
{
  if(n>0)
  {
      a=n/2;

      n=n%2;
if(a>0)
{


      convertbinary(a);
}

  }

    cout<<n;

}




int main()
{
int n=78;//any no you want 
convertbinary(n);



   return 0;
}









i have used recursion. check this.
it is giving right ans :)
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
#include <iostream>
#include <string>
#include <bitset>
#include <limits>

int main()
{
	while ( true )
	{
		std::cout << "Enter a number (0 - exit): ";

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

		if ( x == 0 ) break;

		std::bitset<std::numeric_limits<unsigned int>::digits> b( x );

		std::string s = b.to_string();

		s = s.substr( s.find( '1' ) );

		std::cout << s << std::endl;
	}
}
Last edited on
And the approach with recursion

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
#include <iostream>

int main()
{
	struct Convert
	{
		std::ostream & operator ()( int x, std::ostream &os = std::cout ) const
		{
			const unsigned int base = 2;

			unsigned int digit = x % base;

			return ( ( ( x /= base ) == 0 ? os : operator ()( x ) ) << digit );
		}
	};

	while ( true )
	{
		std::cout << "Enter a number (0 - exit): ";

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

		if ( x == 0 ) break;

		Convert()( x );
	}
}
Thanks guys!
Topic archived. No new replies allowed.