fork download
  1. #include <cmath>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. long int convert_base10(const std::string& num, int base)
  6. {
  7. int dig;
  8. long int result = 0;
  9. const int len = num.size();
  10. for (int i = 0; i < len; i++)
  11. {
  12. if ((num[len-i-1] >= 'A') && (num[len-i-1] <= 'F'))
  13. {
  14. dig = num[len-i-1] - 55; // Why the magic number?
  15. }
  16. else
  17. {
  18. dig = num[len-i-1] - 48;
  19. }
  20. result += dig * pow(base, i);
  21. }
  22. return result;
  23. }
  24.  
  25. void convert_basei(long int num, int base, std::string& result)
  26. {
  27. char rem;
  28. result = "";
  29. while (num)
  30. {
  31. if ((num % base) >= 10)
  32. {
  33. rem = (num % base) + 55;
  34. }
  35. else
  36. {
  37. rem = (num % base) + 48;
  38. }
  39. result.insert(0, 1, rem);
  40. num /= base;
  41. }
  42. }
  43.  
  44. int main()
  45. {
  46. std::string result, num;
  47. int base1, base2;
  48. while (std::cin >> num >> base1 >> base2)
  49. {
  50. long int temp = convert_base10(num, base1);
  51. convert_basei(temp, base2, result);
  52. std::cout << "The result is [" << result<< "]." << std::endl;
  53. }
  54. std::cout << "Failed to parse input." << std::endl;
  55. }
  56.  
Success #stdin #stdout 0s 2992KB
stdin
1111000  2 10
1111000  2 16
2102101  3 10
2102101  3 15
  12312  4  2
     1A 15  2
1234567 10 16
   ABCD 16 15
stdout
The result is [120].
The result is [78].
The result is [1765].
The result is [7CA].
The result is [110110110].
The result is [11001].
The result is [12D687].
The result is [D071].
Failed to parse input.