题目:
编写函数htoi(s),把由十六进制数字组成的字符串(包含可选的前缀0x或0X)转换为与之等价的整型值。字符串中允许包含的数字包括:0~9、a~f以及A~F。
自我解答:
编程思路:
首先函数定义为 int htoi(const char s[]),输入参数用const加以声明,防止在函数内部对其改动;其次返回值为int型,当输入字符串有效时,输出相应的转换值,有无效字符时返回-1并抛出异常;
#include <stdio.h>
/* convert a hex string to digit */
int htoi(const char s[])
{
int i = 0;
int hex = 0;
bool skipHeader = false; /* judge the header is 0x or 0x */
while(s[i] != '\0')
{
if(!skipHeader && s[0] == '0' && (s[1] == 'x' || s[1] == 'X'))
{
skipHeader = true;
if(s[2] == '\0') /* no digit after 0x or 0x */
{
printf("lack of digits after 0x or 0X\n");
hex = -1;
break;
}
else
{
i = 2; /* skip header:0x or 0X */
continue;
}
}
else
{
if(s[i] >= '0' && s[i] <= '9')
{
hex = hex * 16 + (s[i] - '0');
}
else if(s[i] >= 'a' && s[i] <= 'f')
{
hex = hex * 16 + (s[i] - 'a' + 10);
}
else if(s[i] >= 'A' && s[i] <= 'F')
{
hex = hex * 16 + (s[i] - 'A' + 10);
}
else