程序代码:
#include <stdio.h>
#include <string.h>
#define _NG 0xFF
const unsigned char g_hex_charset[] = {
/* 0x00~0x0F */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x10~0x1F */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x20~0x2F */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x30~0x3F */0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x40~0x4F */_NG, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x50~0x5F */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x60~0x6F */_NG, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x70~0x7F */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x80~0x8F */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0x90~0x9F */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0xA0~0xAF */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0xB0~0xBF */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0xC0~0xCF */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0xD0~0xDF */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0xE0~0xEF */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG,
/* 0xF0~0xFF */_NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG, _NG
};
#define hexval(_idx) g_hex_charset[(_idx)]
#ifdef __DEBUG
#define _DBG(fmt, ...) printf("[%s:%d]"fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#define _DBG(fmt, ...)
#endif
int con_16_to_10(char* str)
{
int i, tmp, bits, result = 0;
int len = strlen(str);
if (len < 3) {
_DBG();
return -1;
}
if ((str[0] != '0') || ((str[1]|0x20) != 'x')) {
_DBG();
return -1;
}
for (i = len - 1; i > 1; i--) {
tmp = hexval(str[i]);
if (tmp == _NG) {
_DBG("invalid char: %c", str[i]);
return -1;
}
bits = (len - 1 - i) * 4;
result += tmp * (bits?(1 << bits):1);
_DBG("tmp=%dx2^%d, result=%d\n", tmp, bits, result);
}
return result;
}
int main(void)
{
int value;
char str[100];
scanf("%s", str);
value = con_16_to_10(str);
printf("%d\n", value);
}