C++ Program to Convert Binary Number to Decimal and vice-versa

Updated on December 10, 2024
Convert binary number to decimal and vice-versa header image

Introduction

Binary and decimal number systems are fundamental in computing and digital electronics. While binary (base-2) represents values using two symbols, typically 0 and 1, decimal (base-10) uses ten symbols, from 0 to 9. Understanding how to convert between these systems is not only essential for academic purposes but also provides a solid foundation for understanding how computers process data internally.

In this article, you will learn how to convert binary numbers to decimal and vice versa using C++. Examples will guide you through writing the functions needed for these conversions, enhancing your understanding of data representation and manipulation in programming.

Converting Binary to Decimal in C++

Understanding Binary to Decimal Conversion

  1. Recall that in binary, each digit represents an exponent of 2. The rightmost digit represents 2^0, the next one 2^1, and so on.
  2. To convert binary to decimal, multiply each digit of the binary number by its corresponding power of 2 and sum all these values.

Example: Binary to Decimal Function

  1. Define a function that takes a string representing a binary number and returns an integer decimal number.

  2. Use a loop to traverse each character of the binary string from right to left, converting and calculating as going.

    cpp
    #include <iostream>
    #include <cmath> // for pow function
    
    int binaryToDecimal(const std::string &binary) {
        int decimal = 0;
        int length = binary.length();
        for (int i = 0; i < length; ++i) {
            if(binary[i] == '1') {
                decimal += static_cast<int>(pow(2, length - i - 1));
            }
        }
        return decimal;
    }
    

    In this function, iterate through the binary string, and for each '1' encountered, add 2 raised to the appropriate power to decimal. The static_cast<int> is used to ensure the result of pow is treated as an integer.

Converting Decimal to Binary in C++

Understanding Decimal to Binary Conversion

  1. Recognize that to convert a decimal number to binary, repeatedly divide the number by 2.
  2. Record the remainder for each division. This forms the binary digits from right to left.

Example: Decimal to Binary Function

  1. Define a function to convert an integer decimal number to a binary string.

  2. Utilize a loop to handle the division by 2 and accumulate remainders until the division yields zero.

    cpp
    #include <iostream>
    #include <string>
    #include <algorithm> // for reverse function
    
    std::string decimalToBinary(int decimal) {
        std::string binary = "";
        while (decimal > 0) {
            binary += (decimal % 2) ? '1' : '0';
            decimal /= 2;
        }
        std::reverse(binary.begin(), binary.end());
        return binary.empty() ? "0" : binary;
    }
    

    This function continuously divides the decimal number by 2 and appends '1' or '0' to the binary string based on the remainder. The std::reverse call reverses the string at the end since the binary digits are collected in reverse order.

Practical Application of Functions

Testing the Conversion Functions

  1. Write a simple main function to test conversion from binary to decimal and vice versa.

  2. Provide user the ability to input values and view converted results.

    cpp
    int main() {
        std::string binary;
        int decimal;
    
        std::cout << "Enter a binary number: ";
        std::cin >> binary;
        std::cout << "Decimal: " << binaryToDecimal(binary) << std::endl;
    
        std::cout << "Enter a decimal number: ";
        std::cin >> decimal;
        std::cout << "Binary: " << decimalToBinary(decimal) << std::endl;
    
        return 0;
    }
    

    Compile and run the program to ensure that both functions perform as expected, converting numbers accurately between binary and decimal formats.

Conclusion

Mastering conversions between binary and decimal forms is a useful skill in C++, enhancing comprehension of number systems used in computing. By implementing the example functions in your C++ programs, you gain valuable practice in handling data transformations. Whether used for educational purposes or integrated into larger projects, these conversions are essential in the groundwork of computer science and programming proficiency in C++. Continue exploring these concepts to develop more efficient and effective programming solutions.