How to convert binary number to decimal in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>
  
using namespace std;
  
int binary_to_decimal(string s) { 
    int dec = 0;

    for (int i = s.length() - 1, j = 0; i >= 0; i--, j++) { 
        if (s[i] == '1') {
            dec += pow(2, j); 
        }
    } 
    return dec; 
} 
    
int main() 
{ 
    string s = "10101011";  
  
    cout << binary_to_decimal(s) << endl; 
} 
  
  
  
/*
run:
  
171
  
*/

 



answered May 9, 2019 by avibootz
edited May 9, 2019 by avibootz

Related questions

1 answer 148 views
2 answers 187 views
2 answers 179 views
1 answer 131 views
131 views asked Aug 24, 2021 by avibootz
2 answers 281 views
281 views asked Aug 24, 2021 by avibootz
1 answer 220 views
1 answer 230 views
...