标签:
htoi的实现
1 /*************************************************************************
2 > File Name: htoi.c
3 > Author: ChenPeng
4 > Mail:479103815@qq.com
5 > Blog: http://www.cnblogs.com/cpsmile/
6 > Created Time: Fri 03 Apr 2015 07:22:15 PM CST
7 ************************************************************************/
8 #include<stdio.h>
9 #include<stdlib.h>
10
11 #define YES 1
12 #define NO 0
13
14 /*将十六进制数字组成的字符串转换为与之等价的整型值*/
15 int htoi(char *str)
16 {
17 int hexdigit;//记录每一个十六进制数对应的十进制数
18 int i;//工作指针
19 int ishex;//是否是有效的十六进制数
20 int n;//返回的十进制数
21
22 i= 0;
23 if(str[i] == ‘0‘)
24 {
25 ++i;
26 if(str[i] == ‘x‘ || str[i] == ‘X‘)
27 ++i;
28 }
29 n = 0;
30 ishex = YES;
31 for(; ishex == YES; ++i)
32 {
33 if(str[i] >= ‘0‘ && str[i] <= ‘9‘)
34 hexdigit = str[i] - ‘0‘;
35 else if(str[i] >= ‘a‘ && str[i] <= ‘f‘)
36 hexdigit = str[i] - ‘a‘ + 10;
37 else if(str[i] >= ‘A‘ && str[i] <= ‘F‘)
38 hexdigit = str[i] - ‘A‘ + 10;
39 else
40 ishex = NO;
41 if(ishex == YES)
42 n = 16 * n + hexdigit;
43 }
44 return n;
45 }
46
47 int main()
48 {
49 char str[30] = "";
50 int val;
51 while(printf("Please enter a hex string:\n"),scanf("%s",str) == 1)
52 {
53 val = htoi(str);
54 printf("整数是:%d\n",val);
55 }
56 return 0;
57 }
标签:
原文地址:http://www.cnblogs.com/cpsmile/p/4390900.html