0

I am writing a function in C++ to convert a number from some base to decimal. It works fine when the number of digits is even, but when it is odd it gives wrong answer.

For example:

Number to convert : 100 
Base to convert to: 10
Correct answer    : 100
Function's output : 99

Here is the code:

unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
       std::string characters = "0123456789abcdef";
       unsigned long long res = 0;

       for(int i = 0, len = number.size(); i<len; ++i)
       {
           res += characters.find(number.at(i))*std::pow(base, len-1-i);
       }
       return res;
}

I'm using g++ C++11.

darkpsychic
  • 188
  • 2
  • 8

1 Answers1

4

I can't reproduce your particular issue, but std::pow returns a floating point number and your implementation may have introduced some sort of rounding error which leaded to a wrong result when converted to unsigned long long.

To avoid those errors, when dealing with integer numbers, you should consider to avoid std::pow at all. Your function, for example, could have been written like this:

#include <iostream>
#include <string>
#include <cmath>

unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
    std::string characters = "0123456789abcdef";
    unsigned long long res = 0;
    unsigned long long power = 1;

    for(auto i = number.crbegin(); i != number.crend(); ++i)
    {
        // As in your code, I'm not checking for erroneous input
        res += characters.find(*i) * power;
        power *= base;
    }
    return res;
}

int main ()
{
    std::cout << convertToDecimal("100", 2) << '\n';      // --> 4
    std::cout << convertToDecimal("1234", 8) << '\n';     // --> 668
    std::cout << convertToDecimal("99999", 10) << '\n';   // --> 99999
    std::cout << convertToDecimal("fedcba", 16) << '\n';  // --> 16702650
}
Bob__
  • 12,361
  • 3
  • 28
  • 42