C/C++编程日记:十六进制字符串转换为十进制整数(代码实现)
代码实现十六进制字符串转换为十进制整数的方法,具体实现如下:
/** 将十六进制数字组成的字符串(包含可选的前缀0x或0X)转换为与之等价的整型值*/#include <stdio.h>#include <math.h>/* 将十六进制中的字符装换为对应的整数 */int hexchtoi(char hexch ){ char phexch[] = "ABCDEF"; char qhexch[] = "abcdef"; int i; for(i=0;i<6;i++){ if((hexch == phexch[i]) || (hexch == qhexch[i])) break; } printf("i=%d",i); if(i >= 6){ return 0; /* 非十六进制字符 */ } return 10+i;}int htoi(char s[]){ int n=0; /*有n位*/ int valu=1; /*是否有效*/ int i=0,j; int answer=0; /* 有效性检查 */ if((s[0] == '0') && ((s[1] == 'x') || (s[1] == 'X'))){ i += 2; } while((s[i] != '\n')){ if((s[i] < '0') && (s[i] > '9')){ if(hexchtoi(s[i]) == 0){ valu=0; break; } } n++; i++; } if(valu != 0){ for(j=0;j<n;j++){ answer += ((int)pow(16,j) * hexchtoi(s[i-j-1])); } } else answer = -1; return answer;}main(){ char *n[] = {"0x7ff0","0x2341"}; printf("%s is %d\n",n[0],htoi(n[0])); printf("%s is %d\n",n[0],123);}
赞 (0)