Decimal to Binary

I tired to make a c++ program that converts decimal numbers into binary, I got it right but the thing is when I input a number lets say 4 it gives the binary equivalent backwards 001 while it should give 100.

This is The code:

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>
#include <string>
using namespace std;

int main()
{
	int DecNumber;
	
	cout << "Enter Decimal Number: \n";
	cin >> DecNumber;
	
			 
	for (int beg = 1; beg <= 1; beg++) 
{
	
			if ( DecNumber % 2 == 0)
			{
				printf("0");
				beg--;
			}
				else 
				{
		
					printf("1");
					beg--;	
				}
			
	DecNumber = DecNumber / 2;
		
			if ( DecNumber == 0 )
			{
				cout << '\n';
				break;
			}
						

}
	
	
	return 0;
}
Last edited on
First a tip: please use the code tags to make your code easier to read. See http://www.cplusplus.com/articles/jEywvCM9/

Your for-loop looks really complicated. Consider a while.

Do not mix stdout (printf) and stream (cout).

The modulus tells you the least significant bit and the division discards it. That is why your loop operates "in reverse".

You include <string>, but don't use it. You could add the digits to the string and then print it. That would allow reversal of order.
Thank you for replying and I did add them to a string and found another way with the <algorithm> that has the reverse function which is very helpful.

Is it bad to mix between stdout (printf) and stream (cout)?

And Thanks about the tip, i didn't know about the tags because I am new to this website.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using std::cin;
using std::cout;

void bits(unsigned x)
{
    if (x > 1) bits(x >> 1);
    cout << (x & 1);
}

int main()
{
    unsigned x;
    cout << "Enter number: \n";
    cin >> x;
    bits(x);
    cout << '\n';
}
closed account (3hM2Nwbp)
1
2
3
4
5
6
7
8
9
10
#include<iostream>
#include<bitset>

int main()
{
    int i;
    std::cin >> i;
    std::bitset<32> bits(i);
    std::cout << i << "-->" << bits << std::endl;
}
Topic archived. No new replies allowed.