C++ Code for Converting Decimal to Binary
This article provides a comprehensive guide on converting decimal numbers to binary numbers using C++. We will explore two popular methods:
1. Using the %
and /
Operators
This method involves repeatedly dividing the decimal number by 2 and keeping track of the remainders. The remainders, in reverse order, form the binary equivalent.
Code:
#include
using namespace std;
int main() {
int decimalNum, binaryNum[32] = {0}; // Array to store binary digits
int i = 0;
cout << "Enter a decimal number: ";
cin >> decimalNum;
while (decimalNum > 0) {
binaryNum[i] = decimalNum % 2; // Get remainder
decimalNum /= 2; // Divide by 2
i++;
}
cout << "Binary equivalent: ";
// Print the binary digits in reverse order
for (int j = i - 1; j >= 0; j--) {
cout << binaryNum[j];
}
cout << endl;
return 0;
}
Explanation:
- The
while
loop iterates until the decimal number becomes 0. - In each iteration, we calculate the remainder (
decimalNum % 2
) and store it in thebinaryNum
array. - We then divide the decimal number by 2 (
decimalNum /= 2
) for the next iteration. - The
for
loop prints the binary digits in reverse order, starting from the last calculated remainder.
2. Using Bitwise Operators
Another efficient way is to use the bitwise &
operator and repeatedly shift the decimal number to the right.
Code:
#include
using namespace std;
int main() {
int decimalNum;
cout << "Enter a decimal number: ";
cin >> decimalNum;
cout << "Binary equivalent: ";
// Iterate through all bits
for (int i = 31; i >= 0; i--) {
// Check if the ith bit is set
if ((decimalNum >> i) & 1) {
cout << "1";
} else {
cout << "0";
}
}
cout << endl;
return 0;
}
Explanation:
- The
for
loop iterates through 32 bits (for a 32-bit integer). - We use
(decimalNum >> i) & 1
to check if the ith bit is set. If it is set, we print "1"; otherwise, we print "0". - The
>>
operator shifts the decimal numberi
positions to the right, isolating the ith bit. - The
& 1
operation checks if the isolated bit is 1.
Conclusion
Both methods effectively convert decimal to binary. The %
and /
approach is more intuitive for beginners, while the bitwise operator method offers a concise and efficient solution. Choose the method that best suits your understanding and requirements.