二话不说,直接上干货:
十进制转换2-9,16,32,36进制:
std::string HexConverter::Transform(unsigned int n, int base)
{
unsigned int num[CONVERTER_MAX_LEN] = { 0 }, i = 0, j, m = n;
do
{
i++;
num[i] = m%base; // 保存余数
m = m / base;
} while (m != 0);
std::string endnum = "";
for (j = i; j >= 1; j--) // 将余数序列反序输出
{
if (num[j] < 10)
{
endnum += utility::toString(num[j]); // 如果是0-9数字则直接输出数字
}
else
{
endnum += char(num[j] + 'A' - 10); // 如果是大于9的数字则转化为字符输出
}
}
return endnum;
}
36进制转换10进制:
int HexConverter::Transform(std::string str)
{
char *c = new char[CONVERTER_MAX_LEN]; int i; bool b = false;
for (i = 0; i < str.size(); i++)
{
c[i] = str[i];
}
for (i = 0; i<str.size(); i++)
{
if ((c[i] >= 'a'&&c[i] <= 'z') || (c[i] >= 'A'&&c[i] <= 'Z') || (c[i] >= '0'&&c[i] <= '9'))
{
if (c[i] >= 'A'&&c[i] <= 'Z')
{
c[i] += ('a' - 'A');
}
}
else
{
return 0;
}
}
int m = i; double t = 0, tas = 0, dt = 0;
b = false;
unsigned int tamp = 0;
for (i = 0; i<str.size(); i++)
{
if (c[i] >= 'a'&&c[i] <= 'z')
{
t = ((10 + c[i] - 'a')*pow(36, m - i - 1));
}
if (c[i] >= '0'&&c[i] <= '9')
{
t = ((c[i] - '0')*pow(36, m - i - 1));
}
if (4294967295 - t - tas >= 0)
{
tamp += (int)t;
tas = tamp;
}
else
{
float ff = tamp;
dt += (ff + t);
tamp = 0;
tas = dt;
b = true;
}
}
if (b)
{
char *c = new char[CONVERTER_MAX_LEN];
sprintf(c, "%f", dt);
for (i = 0; c[i] != 0; i++)
{
if (c[i] == '.')
{
c[i] = 0; break;
}
}
return atoi(c);
}
else
{
return tamp;
}
}
其中: #define CONVERTER_MAX_LEN 20