十进制字符串转换为十进制数
char *str = "123";
int n = atoi(str);
printf("%d
", n);
//输出:123
十六进制字符串转换为十进制数
法一
long long change_num(char *str, int length)
{
char revstr[16] = {0}; //根据十六进制字符串的长度,这里注意数组不要越界
long long num[16] = {0};
long long count = 1;
long long result = 0;
strcpy(revstr, str);
for(int i = length - 1; i >= 0; i--)
{
if((revstr[i] >= '0') && (revstr[i] <= '9'))
{
num[i] = revstr[i] - 48; //字符0的ASCII值为48
}
else if((revstr[i] >= 'a') && (revstr[i] <= 'f'))
{
num[i] = revstr[i] - 'a' + 10;
}
else if((revstr[i] >= 'A') && (revstr[i] <= 'F'))
{
num[i] = revstr[i] - 'A' + 10;
}
else
{
num[i] = 0;
}
result += num[i] * count;
count *= 16; //十六进制(如果是八进制就在这里乘以8)
}
return result;
}
int main()
{
char *str = "0xA";
int n = 0;
n = change_num(str, strlen(str));
printf("%d
", n);
return 0;
}
//输出:10
法二
char *str = "0xA";
int n = 0;
sscanf(str, "%x", &n);
printf("%d
", n);
//输出:10
法三
char *str = "0xA";
int n = strtol(str, NULL, 16);
printf("%d
", n);
//输出:10