Binary to decimal conversion

Converting a binary string to its equivalent decimal number

The idea behind converting a binary string to a decimal number is as below
Starting with the least significant (rightmost) bit we multiple each binary digit with the power of 2 starting with 0. As we move towards the most significant (leftmost) bit we increase the power of 2 by 1. The resultant decimal number is the addition of all the multiplications.
Example : Binary string (0110)
resultant decimal = 0 . 2^3 + 1 . 2^2 + 1 . 2^1 + 0 . 2^0
resultant decimal = 6

Optimized algorithm : Binary to decimal conversion
1)    Initialize the equivalent decimal number i.e the result to 0.
2)   For each position of the binary digit starting with the leftmost digit do :
          result = (result * 2) + current binary digit (i.e 0 or 1).
3)    result is the equivalent decimal number.

Example : Consider a binary string : [ 0 1 1 0 ]

Bit Position Bit Intermediate Result
(Result * 2) + Current Bit
Result
0 (leftmost) 0 0 * 2 + 0 0
1 1 0 * 2 + 1 1
2 1 1 * 2 + 1 3
3 (rightmost) 0 3 * 2 + 0 6

Equivalent decimal number : 6

Time Complexity : O(n), where n is the length of the binary string.


C++ : Converting a binary string to a decimal number in C++11

#include<iostream>
#include<string>

using namespace std;

int Binary_To_Decimal(string binary_string) {

    int result = 0;

    for (int i=0; i < binary_string.size(); i++) {
        result = (result << 1) + (binary_string.at(i) == '1');
    }
    return result;
}

int main()
{
    string binary_string;

    cout << "Enter binary string : ";
    cin >> binary_string;
    cout << "Equivalent decimal number : " << Binary_To_Decimal(binary_string) << endl;

    return 0;
}

Output of binary to decimal conversion

Enter binary string : 100000000
Converted decimal number : 256

Enter binary string : 0101
Converted decimal number : 5

Enter binary string : 10
Converted decimal number : 2


Copyright (c) 2020, Algotree.org.
All rights reserved.