Algorithm to Convert Binary Numbers to Decimal

  • Initialize a variable dec_value to store the decimal representation and a variable base to keep track of the current binary place.
  • Run a loop till num is non-zero,
    • Extract the last digit of num and store it in a variable last_digit.
    • Update num by removing the last digit.
    • Add last_digit * base (power of 2) to dec_value to calculate the decimal value of the current binary place.
    • Update the base by multiplying it by 2.
  • Return dec_value as it holds the decimal representation of the binary number.

Example

The below diagram explains how to convert ( 1010 ) to an equivalent decimal value.

C++ Program For Binary To Decimal Conversion

The binary number system uses only two digits 0 and 1 to represent an integer and the Decimal number system uses ten digits 0 to 9 to represent a number. In this article, we will discuss the program for Binary to Decimal conversion in C++.

Similar Reads

Algorithm to Convert Binary Numbers to Decimal

Initialize a variable dec_value to store the decimal representation and a variable base to keep track of the current binary place. Run a loop till num is non-zero, Extract the last digit of num and store it in a variable last_digit. Update num by removing the last digit. Add last_digit * base (power of 2) to dec_value to calculate the decimal value of the current binary place. Update the base by multiplying it by 2. Return dec_value as it holds the decimal representation of the binary number....

C++ Program to Convert Binary Numbers to Decimal

C++ // C++ program to convert binary // to decimal #include using namespace std;    // Function to convert binary // to decimal int binaryToDecimal(int n) {     int num = n;     int dec_value = 0;        // Initializing base value to     // 1, i.e 2^0     int base = 1;        int temp = num;     while (temp) {         int last_digit = temp % 10;         temp = temp / 10;         dec_value += last_digit * base;         base = base * 2;     }        return dec_value; }    // Driver code int main() {     int num = 10101001;     cout << binaryToDecimal(num) << endl; }...

Convert Binary Numbers to Decimal Using std::bitset Class

...