#include <stdio.h>
#include <math.h>
int OX2Ten(char[]);
int Char2Int(char);
int main(int argc,char *argv[])
{
char ch[10];
int result;
printf("please input a HEX number:");
gets(ch);
result = OX2Ten(ch);
if (-1 != result)
{
printf("the result is : %d",result);
}
else
{
printf("error: you input HEX number is error.");
}
system("pause");
return 0;
}
int OX2Ten(char ch[])
{
int i,j = 0;
int result = 0,int10value;
for (i = strlen(ch) - 1; i >= 0 ;i--,j++)
{
int10value = Char2Int(ch[i]);
if (-1 != int10value)
{
result += pow(16,j) * int10value;
}
else
{
result = -1;
break;
}
}
return result;
}
int Char2Int(char c)
{
int result = -1;
if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
{
switch(c)
{
case 'a':
case 'A':
result = 10;
break;
case 'b':
case 'B':
result = 11;
break;
case 'c':
case 'C':
result = 12;
break;
case 'd':
case 'D':
result = 13;
break;
case 'e':
case 'E':
result = 14;
break;
case 'f':
case 'F':
result = 15;
break;
}
}
else if (c >= '0' && c <= '9')
{
result = c - 48 ;
}
else
{
;
}
return result;
}
|