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. ):
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.
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"
Look at the type of variable "bin". It is a std::string.
The "1" and "0" are constant C-string literals, with type constchar *.
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?
usingnamespace 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];
}
}
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.