I made a header file to convert strings to numbers of base X. That is I want:

``int num=B<16,int>("FFF");``

To equal:

``int num=0xFFF;``

Here is the code so far:

``````#include <string>
int numb(char in)
{
if (in>='0'&&in<='9')
return in-'0';
else if (in>='a'&&in<='z')
return in-'a';
else if (in>='A'&&in<='Z')
return in-'A';
}
template <typename T>
T pow(T n1, T n2)
{
T temp=n1;
for (T i=0; i<n2; i++)
temp*=n1;
return temp;
}
template <const int base,typename T>
T B(std::string num)
{
T ret=0;
for (int i=0; i<num.length(); i++)
ret+=numb(num[num.length()-i-1])*pow(T(base),T(i));
return ret;
}``````

The problem is that it isn't working. Can anybody see why?

Nevermind, I posted too soon. Just figured it out:

``````#include <string>
int numb(char in)
{
if (in>='0'&&in<='9')
return in-'0';
else if (in>='a'&&in<='z')
return in-'a';
else if (in>='A'&&in<='Z')
return in-'A';
else
return 0;
}
template <typename T>
T pow(T n1, T n2)
{
if (n2==0)
return 1;
else if (n2==1)
return n1;
else
return pow<T>(n1, n2-1)*n1;
}
template <const int base,typename T>
T B(std::string num)
{
T ret=0;
for (int i=0; i<num.length(); i++)
ret+=numb(num[num.length()-i-1])*pow(T(base),T(i));
return ret;
}``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.