#include
#include
#include
int main(void)
{
long int digital, len, times;
char ch[50];
while (true)
{
fputs("请输入一个十六进制数字 <#退出> : ", stdout);
gets(ch);
for (times = 1, len = strlen(ch) - 1, digital = 0; len >= 0; --len)
{
ch[len] = tolower(ch[len]);
if (ch[len] >= 'a' && ch[len] <= 'f')
digital += (ch[len] - 87) * times;
else if (isdigit(ch[len]))
digital += (ch[len] - 48) * times;
else
{
puts("无法识别的十六进制!");
break;
}
times *= 16;
}
printf("%s = %d\n\n", ch, digital);
}
return 0;
}
#include
#include
#define N 8
int main()
{
char data[N];
int sum = 0;
char is_error = 0;//标记输入的字符是否正确
int count = 0;
if (0 == scanf("%s", data, sizeof(data)))
{
is_error = 1;//读取错误
}
count = strlen(data);
for (int i = 0; i < count; ++i)
{
int num = 0;
if (data[i] >= 48 && data[i] <= 57)//0-9字符
{
num = data[i] - 48;
}
else if (data[i] >= 65 && data[i] <= 70)//A-F字符
{
num = data[i] - 65 + 10;
}
else if (data[i] >= 97 && data[i] <= 102)//a-f字符
{
num = data[i] - 97 + 10;
}
else//非法字符
{
is_error = 1;
}
for (int j = 1; j < count-i; ++j)
{
num *= 16;
}
sum += num;
}
if (1 == is_error)
{
printf("illegal string!\n");
}
else
{
printf("%d\n", sum);
}
}