Cover Image for Decimal to Binary in C++
78 views

Decimal to Binary in C++

To convert a decimal number to binary in C++, you can use the following algorithm:

  1. Initialize an empty string to store the binary representation.
  2. Keep dividing the decimal number by 2 and appending the remainder (0 or 1) to the string.
  3. Continue this process until the decimal number becomes 0.
  4. 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:

  1. The decimalToBinary function takes an integer decimalNumber as input and returns its binary representation as a string.
  2. It iteratively divides the decimal number by 2, appending the remainder to the binaryResult string until the decimal number becomes 0.
  3. After the loop, the string is reversed to obtain the correct binary representation.
  4. The main function prompts the user to enter a decimal number, calls the decimalToBinary function, and displays the binary representation.

Compile and run this program, and it will convert a decimal number to its binary equivalent.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS