fork(9) download
  1. #include <iostream>
  2. #include <string>
  3. #include <cmath>
  4. #include <exception>
  5. using namespace std;
  6.  
  7. int bintodec(string binary, unsigned int i = 0)
  8. {
  9. int tot = 0;
  10. if (i < binary.length())
  11. {
  12. if (binary[i] == '1')
  13. tot = pow(2, i);
  14. else if (!binary[i] == '0')
  15. throw "String is not formatted in binary";
  16. return tot + bintodec(binary, ++i);
  17. }
  18. return tot;
  19. }
  20.  
  21. int main() {
  22. string binary = "1011";
  23. int dec = bintodec(binary);
  24. cout << dec << endl;
  25. return 0;
  26. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
13