Help with reversing order of my decimal to binary program?

Hello guys. I managed to do a program which allows you to input a decimal and it converts it to binary. But the problem is, I need the numbers to show up in a reversed order. When I type, '19', it shows: 11001 instead of 10011. Any help would be really appreciated ^^ I've tried searching online but they're either to complicated or they don't explain the reason for doing this and such. ):

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
#include "stdafx.h"
#include<iostream>
#include <stdio.h>
#include <conio.h>
#include <string>


using namespace std;

int main()
{
    int decimalNumber;
    int binaryNumber;


    printf("Enter any decimal number: ");
    scanf("%d",&decimalNumber);

  

    while(decimalNumber!=0){
        binaryNumber= decimalNumber % 2;
        decimalNumber = decimalNumber / 2;

		cout << binaryNumber;
    }



    getch();
}
You do start from the least significant bit and print it immediately, so of course it prints out in the reverse order. You should store the bits somehow and print them laterr, when you have all of them. There are many ways to do it.



PS. You do mix C and C++ style I/O. That is not good.
Can you enlighten me with some of the ways? They would really be helpful. :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main()
{
	int dec;
	string bin;

	cout << " decimal number: ";
	cin  >> dec;

	while(dec != 0)
	{
	    if (dec % 2 == 1)
            bin = "1" + bin;
        else
            bin = "0" + bin;

            dec = dec / 2;
	}
    cout << endl << bin << endl;
    return 0;
}

Thank you for this insight. It works perfectly, thank you! ^^ But I was just wondering...

What does the:

bin = "1" + bin;

and the

bin = "0" + bin;

do?
Inserts at the beginning of the string a new character.
bin = bin + "1" would add it to the end,
so if bin = "HELLO"
after
bin = "1" + bin
it would become
"1HELLO"
Whereas with
bin = bin + "1"
it would become
"HELLO1"
Last edited on
Look at the type of variable "bin". It is a std::string.
The "1" and "0" are constant C-string literals, with type const char *.
The std::string provides operator+ that accepts const char * and std::string and returns a new std::string that holds concatenation of the two operands.
See http://www.cplusplus.com/reference/string/string/operator+/

In other words "1" + bin creates a (unnamed temporary) string object that has "1" prepended to the text that the bin holds.

The bin = ... assigns the new value to bin.


This is one way to do it. The std::string bin stores an array of characters, and the program stores new bits (as characters) at the left end of the array.


There is an another way. Add the bits into a number. How would you create (decimal) number 10011 from the bits of value 19?


There is a third way too: recursion.
Last edited on
Ohhh :O I see. It's much clearer now, thank you for the information everyone! ^^ I've heard of recursion but I never really tried it yet...
With the internet as a resource you hardly need a beginner's forum as the answer is usually somewhere to be found. For example the recursive version of a decimal to binary conversion.
http://groups.engin.umd.umich.edu/CIS/course.des/cis400/cpp/binary.html
Dear,
I wrote this program few days ago, please check it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using namespace std;
#include <iostream>
main()
{
	int num1, binary[100];
	cout << "Please end any decimal number" << endl;
	cin >> num1; // For example, user entered "19"
	int num2 = 0; // Use for binary array to start with zero
	
	// Do while loop till Quotient less than 2.
	do {
		binary[num2] = num1%2; 	// taking remainder & store in array
		num1 = num1/2; 		// taking quotient
		num2++; 		// increment in binary array
	} while (num1<<2); 		// Apply condition to stop the while loop  
	
	// print all remainders is reverse order (down to up)
	for (int num3=num2-1; num3>=0; num3--) 
	{	
		cout << binary[num3];
	}
}
Last edited on
Line 1. One should avoid the using namespace std;, but if it is used, it should be after included headers.

Line 3. Standard forbids main() without return type (and there is only one valid return type).

Line 5. How many bits does int have?

Line 6. "End" a number?

Line 7. What if input fails, or the user types a negative number?

Line 15. Please explain what the condition does.

Lines 14 and 18. The style guideline is to use pre-operators by default and post-operators only when really necessary.

Line 21½. Explicit return 0; is better than implicit. With implicit return it is impossible to know whether you forgot or intentionally omitted it.
I have a question ... @RizwanAnsari...

I understand everything.. except for the:

for (int num3=num2-1; num3>=0; num3--)


... I get that it's for reversing the output.. but why would you want to subtract num2 to the number 1?
The array has num2 elements. What is the index of the last element of such array?


Dear keskiverto, thanks for the correction in above program.
Actually, I am new and have not any experience about c++. This is my first to post any code at any website. I really like you comments.


Line 15: Condition: loop will be end if and only if quotient will be less than 2 as we are working on binary system.

If you have some time then please give me the code with correction.

Less than? Operator<< isn't less than. It is bitshift.
Topic archived. No new replies allowed.