C++ Program For Binary To Decimal Conversion
Given a binary number as input, we need to write a program to convert the given binary number into an equivalent decimal number.
Examples:Â
Input: 111 Output: 7 Input: 1010 Output: 10 Input: 100001 Output: 33
The idea is to extract the digits of a given binary number starting from the rightmost digit and keep a variable dec_value. At the time of extracting digits from the binary number, multiply the digit with the proper base (Power of 2) and add it to the variable dec_value. In the end, the variable dec_value will store the required decimal number.
For Example:Â
If the binary number is 111.Â
dec_value = 1*(2^2) + 1*(2^1) + 1*(2^0) = 7
The below diagram explains how to convert ( 1010 ) to equivalent decimal value:
Below is the implementation of the above idea :Â
C++
// C++ program to convert binary // to decimal #include <iostream> 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; } |
Output:Â
169
Time complexity : O(logn)
Auxiliary Space : O(1)
Note: The program works only with binary numbers in the range of integers. In case you want to work with long binary numbers like 20 bits or 30 bit, you can use a string variable to store the binary numbers.
Below is a similar program which uses string variable instead of integers to store binary value:Â
Â
C++
// C++ program to convert binary to decimal // when input is represented as binary string. #include <iostream> #include <string> using namespace std; // Function to convert binary // to decimal int binaryToDecimal(string n) { string num = n; int dec_value = 0; // Initializing base value to 1, i.e 2^0 int base = 1; int len = num.length(); for ( int i = len - 1; i >= 0; i--) { if (num[i] == '1' ) dec_value += base; base = base * 2; } return dec_value; } // Driver code int main() { string num = "10101001" ; cout << binaryToDecimal(num) << endl; } |
Output:Â
169
Time complexity : O(n) where n is the length of the string.
Auxiliary Space : O(1)
Using pre-defined function:
C++
// C++ program to implement // the above approach #include <iostream> using namespace std; // Driver code int main() { char binaryNumber[] = "1001" ; cout << stoi(binaryNumber, 0, 2); return 0; } |
Output :Â Â
9
Time complexity: O(n) where n is the length of the given string.
Auxiliary Space: O(1)
Please Login to comment...