Program for Decimal to Binary Conversion in C++
Decimal to Binary Conversion
Converting a decimal number to binary involves representing the number in base-2, where each digit is either 0 or 1.
We will explore three methods to perform this conversion using C++ programming.
Method 1: Using Bitwise Operators
We use bitwise operations to extract each bit from the number.
#include <iostream>
using namespace std;
void decimalToBinary_bitwise(int n) {
for (int i = 31; i >= 0; i--) {
cout << ((n >> i) & 1);
}
cout << endl;
}
int main() {
int num;
cout << "Enter a decimal number: ";
cin >> num;
decimalToBinary_bitwise(num);
return 0;
}
Method 2: Using Division by 2
We repeatedly divide the number by 2 and store the remainder.
#include <iostream>
#include <vector>
using namespace std;
void decimalToBinary_division(int n) {
vector binary;
while (n > 0) {
binary.push_back(n % 2);
n /= 2;
}
for (auto it = binary.rbegin(); it != binary.rend(); ++it) {
cout << *it;
}
cout << endl;
}
int main() {
int num;
cout << "Enter a decimal number: ";
cin >> num;
decimalToBinary_division(num);
return 0;
}
Method 3: Using Recursion
We use recursion to keep dividing the number by 2 until it becomes 0, printing the remainder in reverse order.
#include <iostream>
using namespace std;
void decimalToBinary_recursive(int n) {
if (n == 0)
return;
decimalToBinary_recursive(n / 2);
cout << (n % 2);
}
int main() {
int num;
cout << "Enter a decimal number: ";
cin >> num;
if (num == 0)
cout << "0";
else
decimalToBinary_recursive(num);
cout << endl;
return 0;
}