I'm trying to convert integers to binary, using the modulo operator. I get the correct digits, although they are in the incorrect order. For example 76 to binary is 1001100 but the output is 0011001; hence, I have tried to rectify this by outputting 1 if the result is 0 and outputting out 0 if the result is 1, using if-else statements; but the result is then 1100110, which is also wrong.
Here is my code:
include <iostream>
using namespace std;
int main() {
int num;
int remainder;
cout << "Enter a decimal number:" << endl;
cin >> num;
while (num != 0){
remainder = num % 2;
if (remainder == 1 ){
cout << remainder - 1;
}
else if (remainder == 0){
cout << remainder + 1;
}
num = num / 2;
}
return 0;
}
Any suggestions?
2 Answers
Rather than flipping the individual output digits, you need to reverse their order. There are many ways you can do this but one quite 'natural' method is to use a stack – which is an inherently last-in, first-out (LIFO) system.
The C++ Standard Template Library provides a std::stack container, ready-to-use. Here's a working program that does what you want:
#include <iostream>
#include <stack>
using std::cout, std::cin, std::endl; // Pre-C++17, these will need to be separate "using" lines!
using std::stack;
int main()
{
int num;
int remainder;
stack<char> digits;
cout << "Enter a decimal number:" << endl;
cin >> num;
while (num != 0) { // Push the digits onto the stack ...
remainder = num % 2;
digits.push(remainder ? '1' : '0');
num = num / 2;
}
while (!digits.empty()) { // ... then print and pop them (in reverse order)
cout << digits.top();
digits.pop();
}
cout << endl;
return 0;
}
You can use std::bitset. But if you want to do this without using std::bitset, you can push bits to string and reverse it.
Solution without Bitset
#include <iostream>
#include <string>
#include <algorithm>
int main() {
int N, i = 0;
std::cout << "Enter a decimal number:" << std::endl;
std::cin >> N;
std::string res(32, '0');
while (N) {
res[i++] += (N&1);
N >>= 1;
}
std::reverse(res.begin(), res.end());
std::cout << res << std::endl;
}
Solution With Bitset
#include <iostream>
#include <bitset>
int main() {
int N;
std::cout << "Enter a decimal number:" << std::endl;
std::cin >> N;
std::cout << std::bitset<32>(N).to_string() << std::endl;
}