C++

Binary to Decimal Conversion in C++

In the article, we will see the conversion of binary values to decimal values in a C++ program. The binary number is represented by the 0 and 1 digits, whereas the decimal values contain the digits that range from 0 to 9. To accomplish a binary-to-decimal conversion, the binary value should be multiplied by 2 raised to the power of “n” starting from the right and moving leftward with a higher “n”. Let’s implement this in the code to transform a binary to a decimal value.

Example 1: Program of Binary to Decimal Using the “While” Loop

We have a following program to convert the number from binary to decimal. Within the program, we utilize the “while” loop for the binary conversion to decimal.

#include <iostream>
#include <cmath>

using namespace std;

int conversionOfBin(long long);

int main() {
    long long num;
    cout << "Binary Number Required: ";
    cin >> num;
    cout << num << " in binary = " << conversionOfBin(num) << " in decimal";
    return 0;
}

int conversionOfBin(long long num) {
    int deci = 0, x = 0, remainder;

    while (num!=0) {
        remainder = num % 10;
        num /= 10;
        dec += remainder * pow(2, x);
        ++x;
    }

    return deci;
}

Here, we define the “iostream” header file for the input and output streams and the “cmath” to utilize the mathematical function in the program. After that, we define the ConversionOfBin() function where the parameter of type “long long” is passed. Next, we have a main() function call to execute the program. We declare a long inter type variable called “num” inside the main() function.

After this, the ConversionOfBin() function converts the input binary number into the decimal number. For this, we have the definition of the ConversionOfBin() function after the driver code. The ConversionOfBin() function is passed with the “num” variable which has the binary number. Then, we call the “while” loop to transform the binary number in “num” to a decimal value. Before this, we initialize the “deci”, “x,” and “remainder” variables with the value of “0”.

Within the “while” loop, the division operation is conducted to represent the rightmost value of the binary number. The division results are stored in the “remainder” variable. Then, we add the results of the remainder and the power results into the “deci” variable. The “x” variable keeps evaluating the active power of 2.

The results of converting the specified binary numbers to decimal values are achieved in the C++ console:

Example 2: Program of Binary to Decimal Using the “For” Loop

The transformation from binary to decimal was accomplished using a “while” loop. However, we can also use the “for” loop method to transform the binary bits into the decimal number.

#include <iostream>
#include <string>

int main() {
    std::string bin;
    std::cout << "Input Binary Number: ";
    std::cin >> bin;

    int dec = 0;
    int baseIs = 1;

    for (int a = bin.length() - 1; a >= 0; a--) {
        if (bin[a] == '1') {
            dec += baseIs;
        }
        baseIs *= 2;
    }

    std::cout << "Results in Decimal: " << dec << std::endl;

    return 0;
}

Here, we begin with the main() function program where we have the “std::string” variable which is “bin” to store the binary number input by the user in the prompt. Initially, the prompt will ask the user to input the binary number using the “cout” statement. Then, the “cin” command will read that binary number. After that, we initialize the “dec” variable with the value of “0” and the “baseIs” variable with the value of “1” to get the decimal equivalent.

Then, we call a “for” loop which loops over each number of the specified binary from right to left. Within the loop, we have an “if” condition to verify whether the binary number is 1. If it is 1, the decimal value is added to the “dec” variable. The “baseIs” variable has the power of 2 to be multiplied with 1 on each iteration.

The value of the binary number and its conversion into the decimal value is shown on the prompt screen:

Example 3: Program of Binary String to Decimal

The binary string value is now defined to convert its value into the decimal value. The following implementation is done to transform the binary string value to decimal value:

#include <iostream>
#include <string>
using namespace std;

int binToDec(string val)
{
    string value = val;
    int decimal_value = 0;

    int base_value = 1;

    int len = value.length();
    for (int m = len - 1; m >= 0; m--) {
        if (val[m] == '1')
            decimal_value += base_value;
        base_value = base_value * 2;
    }

    return decimal_value;
}

int main()
{
    string val = "11100101";
    cout << binToDec(val) << endl;
}

Here, we begin with creating a BinToDec() function for the conversion of binary digits into decimal values. The BinToDec() function takes the “val” argument of the string type. Within the BinToDec() function, we initialize the “value” variable with the “val” variable which represents that the value of the “val” variable will be stored in the “value” variable. Then, we declare a new variable, “decimal_value”, which is assigned with a value of 0.

Similarly, the “base_value” variable is set and initialized with the value of 1. Next, we define the “len” variable where the length() function is called to get the length of the binary number. After the initialization of the variable, we have the “for” loop iteration. The “for” loop iterates every binary number digit from right to left.

After that, we have a main() function where the binary number is specified as a string value to the “val” variable which is converted into the decimal value as we call the BinToDec(val) function with the “cout” command.

The string-type binary value is now converted into the decimal value as displayed in the following:

Example 4: Program of Binary to Decimal Using the Bitset Class

Additionally, we can convert the binary number into the decimal number by defining the “bitset” class of C++ in the program. It provides the functions through which the conversion procedure is very simple.

#include <iostream>
#include <bitset>

int main() {
    std::string binaryIs;
    std::cout << "Please provide binary number: ";
    std::cin >> binaryIs;

    std::bitset<64> binary(binaryIs);
    unsigned long decimalNumber = binary.to_ulong();

    std::cout << "Decimal Number: " << decimalNumber << std::endl;

    return 0;
}

Here, we set the “bitset” library of C++ in the header which is very helpful when working with binary values. After this, we have a main() function definition where we use the “std::string” to declare the “binaryIs” variable. The “binaryIs” variable stores the value of binary in the string. Next, we ask the user to add the binary number in the prompt by the user and it is read through the “cin” command. After this, we adjust the size of the bits which can be 64 bits integer. Then, the to_ulong() function is called from the “bitset” class into the “decimalNumber” variable. The to_ulong() function converts the set of bits to an unsigned long data type. Lastly, we use the “cout” command to print the decimal value of the binary value that is given by the user.

The binary value provided by the user is now converted into the decimal value:

Conclusion

In conclusion, we covered the methods of converting a binary value to a decimal value. We used the “for” loop, “while” loop, and the bitset class approaches for the binary conversion to decimal. These approaches transform the binary numbers into decimal systems which facilitates reading and comprehension.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content