C++ to achieve hexadecimal string conversion to decimal integer method
- 2020-04-02 03:07:59
- OfStack
This article illustrates the method of converting hexadecimal string into decimal integer in C++. Share with you for your reference. The specific implementation method is as follows:
#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;
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 %dn",n[0],htoi(n[0]));
printf("%s is %dn",n[0],123);
}
Hope that the article described in the C++ programming to help you.