C程序设计语言(第二版):练习2-3
作者:互联网
题目:
编写函数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
{
printf("error: illegal input: %c\n", s[i]);
return -1;
}
i++;
}
}
if(s[0] == '\0')
{
printf("no input\n");
hex = -1;
}
return hex;
}
int main()
{
printf("0x%x\n", htoi("1234"));
printf("0x%x\n", htoi("0x1234"));
printf("0x%x\n", htoi("0"));
printf("0x%x\n", htoi("0x0"));
printf("0x%x\n", htoi("0x1234ab"));
printf("0x%x\n", htoi("0x1234AF"));
printf("0x%x\n", htoi("0x123456789"));
printf("%d\n", htoi("0x"));
printf("%d\n", htoi("0s"));
printf("%d\n", htoi("0x120xab"));
printf("%d\n", htoi(""));
}
运行结果为:
0x1234
0x1234
0x0
0x0
0x1234ab
0x1234af
0x23456789
lack of digits after 0x or 0X
-1
error: illegal input: s
-1
error: illegal input: x
-1
no input
-1
程序中考虑了如下几种情况:
1. 有效数字包含除0~9 a~f A~F之外字符
2. 自动判断是否以0x或0X开头,以及0x或0X之后是否有数字
3. 空字符串的情况
未考虑数据超范围的情况,这种情况会自动截断
参考答案:
标签:const,语言,int,0X,练习,htoi,&&,程序设计,0x 来源: https://blog.csdn.net/yangjingdong2008/article/details/121226594