#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{
int i, j, len, sum = 0;
char s[1000]; //store the 0x number you input
printf("Please input the number you want to chang form 0x(..) to int\n");
scanf("%s", s);
len = strlen(s); //the length of s
if((s[0] == '0') && (s[1] == 'x' || s[1] == 'X')) //check the prefix
{
for(i = len-1; i >= 2; i--)
{
int tmp = 1; //store the 16^x
for(j = len-1; j > i; j--)
{
tmp *= 16;
}
if(s[i] >= '0' && s[i] <= '9')
{
sum += tmp * (s[i] - '0');
}
else if(s[i] >= 'a' && s[i] <= 'f')
{
sum += tmp * (s[i] - 'a' + 10);
}
else if(s[i] >= 'A' && s[i] <= 'F')
{
sum += tmp * (s[i] - 'A' + 10);
}
else
{
printf("Your input is invalid!\n");
return 0;
}
}
printf("The result is %d\n", sum);
}
else
{
printf("Your input is invalid!\n");
}
return 0;
}
只是简单的实现了十六进制向十进制的转换,没有考虑复杂的情况 .
一个将十六进制转换成十进制的小例子
最新推荐文章于 2023-11-15 21:15:01 发布