将16进制字符串值转换为 int 整型值
此例中用 "1de" 作为测试字符串,实现代码如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
-
- int c2i(char ch)
- {
-
- if(isdigit(ch))
- return ch - 48;
-
-
- if( ch < ‘A‘ || (ch > ‘F‘ && ch < ‘a‘) || ch > ‘z‘ )
- return -1;
-
-
-
- if(isalpha(ch))
- return isupper(ch) ? ch - 55 : ch - 87;
-
- return -1;
- }
-
- int hex2dec(char *hex)
- {
- int len;
- int num = 0;
- int temp;
- int bits;
- int i;
-
-
- len = strlen(hex);
-
- for (i=0, temp=0; i<len; i++, temp=0)
- {
-
-
-
- temp = c2i( *(hex + i) );
-
-
-
-
- bits = (len - i - 1) * 4;
- temp = temp << bits;
-
-
- num = num | temp;
- }
-
-
- return num;
- }
-
-
- int main(int argc, char *argv[])
- {
- char ch[10] = {0};
- strcpy(ch, "1de");
- printf("hex:%d\n", hex2dec(ch));
- return 0;
- }
本人在CentOS 6.5下测试
编译:gcc -Wall test.c -ohex
运行:./hex
输出:hex:478
C语言:将16进制字符串转化为int类型值
原文:http://www.cnblogs.com/lidabo/p/3995055.html