您不需要任何指数函数即可将十六进制/二进制字符串转换为数字。只需重复乘以 16:
#include <stdio.h>
unsigned long long hex2num(const char* hex)
{
unsigned long long result = 0;
while (*hex != '\0')
{
char b = *hex;
if (b >= 'a' && b <= 'f') b = b - 'a' + 10;
else if (b >= 'A' && b <= 'F') b = b - 'A' + 10;
else b = b - '0';
result = result * 16 + b;
hex++;
}
return result;
}
const char* const testData[] =
{
"0",
"f",
"1F",
"Ffff",
"FFFFFFFF",
"7fffffffffffffff"
};
int main(void)
{
unsigned i;
for (i = 0; i < sizeof(testData)/sizeof(testData[0]); i++)
printf("\"%s\" = %llu\n", testData[i], hex2num(testData[i]));
return 0;
}
输出:
"0" = 0
"f" = 15
"1F" = 31
"Ffff" = 65535
"FFFFFFFF" = 4294967295
"7fffffffffffffff" = 9223372036854775807
另请注意,乘以 16 相当于向左移动 4 个二进制位置,并且加法b
可以用按位 OR 代替。