118 views
Decimal to Binary in C++
To convert a decimal number to binary in C++, you can use the following algorithm:
- Initialize an empty string to store the binary representation.
- Keep dividing the decimal number by 2 and appending the remainder (0 or 1) to the string.
- Continue this process until the decimal number becomes 0.
- Reverse the string to get the binary representation.
Here’s a C++ program to perform the decimal to binary conversion:
C++
#include <iostream>
#include <string>
#include <algorithm> // for reverse function
std::string decimalToBinary(int decimalNumber) {
if (decimalNumber == 0) {
return "0"; // Special case: 0 in decimal is 0 in binary
}
std::string binaryResult = ""; // Initialize an empty string to store binary
while (decimalNumber > 0) {
// Append the remainder (0 or 1) to the binary string
binaryResult += std::to_string(decimalNumber % 2);
// Divide the decimal number by 2
decimalNumber /= 2;
}
// Reverse the binary string to get the correct binary representation
std::reverse(binaryResult.begin(), binaryResult.end());
return binaryResult;
}
int main() {
int decimalNumber;
std::cout << "Enter a decimal number: ";
std::cin >> decimalNumber;
std::string binaryRepresentation = decimalToBinary(decimalNumber);
std::cout << "Binary representation: " << binaryRepresentation << std::endl;
return 0;
}
In this program:
- The
decimalToBinary
function takes an integerdecimalNumber
as input and returns its binary representation as a string. - It iteratively divides the decimal number by 2, appending the remainder to the
binaryResult
string until the decimal number becomes 0. - After the loop, the string is reversed to obtain the correct binary representation.
- The
main
function prompts the user to enter a decimal number, calls thedecimalToBinary
function, and displays the binary representation.
Compile and run this program, and it will convert a decimal number to its binary equivalent.