I build this function that take a char with a hex value and return the value as an integer, the hex char value can star with 0x
or 0X
and could has lower or upper char, you must check if is a correct hex value if not return -1.
I am asking if you can improve this code or do it in a more efficient way, I can't use c or another library just use the c core. Just c no c++.
long long unsigned int atoi_hexadecimal(char s[])
{
long long unsigned int num = 0;
long long unsigned int size = 0;
long long unsigned i=0;
while(s[i]!='\0')
i++;
size=i;
for(i=0 ; (((s[i]>='0') && (s[i]<='9')) || ((s[i]>='A') && (s[i]<='F')) || ((s[i]>='a') && (s[i]<='f')) || ((s[i]=='x') || (s[i]=='X'))); ++i)
{
if((i==0) && (s[i]!='0'))
return -1;
else if ((i==1) && (s[i]!='x') && (s[i]!='X'))
return -1;
else if ((s[i]>='A') && (s[i]<='F'))
num = num + (s[i]-'A'+10)*power(16,size-i-1);
else if ((s[i]>='a') && (s[i]<='f'))
num = num + (s[i]-'a'+10)*power(16,size-i-1);
else if ((s[i]>='0') && (s[i]<='9') && (i!=0))
num = num + (s[i]-'0')*power(16,size-i-1);
else if ((i!=0) && (s[i]!=0) && (s[i]!='x') && (s[i]!='X'))
return -1;
}
if(i==size)
return num;
else return -1;
}
double power(double base, double exp)
{
double p=1;
for(int i=0; i<exp; i++)
{
p=p*base;
}
return p;
}
Example of use
printf("%llu \n",atoi_hexadecimal("0XF15"));
Can anybody improve this code for transform char that contain a hex to int value or do it in another way?