文章目录
把一个数字转换成16进制数字表示的字符串,我们可以调用sprintf,但是C的标准库里面并没有提供对应的将一个十六进制的字符串型的数字转换成整型数字的函数.以下函数只支持32位。
转换函数
/* input hex string, format: 0xAA111 or AA111 or abc11 */
int ahextoi(char* p)
{
int n = 0;
char* q = p;
/* reach its tail */
while(*q)
q++;
if(*p == '0' && *(p + 1) != 0)
/* skip "0x" or "0X" */
p += 2;
while(*p)
{
int c;
if(*p >= '0' && *p <= '9')
c = *p - '0';
else if(*p >= 'A' && *p <= 'F')
c = *p - 'A' + 0xA;
else if(*p >= 'a' && *p <= 'f')
c = *p - 'a' + 0xA;
else
/* invalid char */
return 0;
n += c << ((int)(q - p - 1) * 4);
p++;
}
return n;
}
测试
int main(int argc, char* argv[])
{
int out = 0;
out = ahextoi("");
printf("%#010X/n", out);
out = ahextoi("0x123");
printf("%#010X/n", out);
out = ahextoi("123abc");
printf("%#010X/n", out);
out = ahextoi("ABC123");
printf("%#010X/n", out);
out = ahextoi("0XAc1b1c");
printf("%#010X/n", out);
return 0;
}