Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to convert hexadecimal string into integer without library function? For example, if "FF" is entered, the conversion result is: 255.
How to convert hexadecimal string into integer without library function? For example, if "FF" is entered, the conversion result is: 255.
# include & ltconio.h & gt

# include & ltstdio.h & gt

long str2num(char *str)

{

char * p = str

Long data = 0;

while (*p)

{

if(* p & gt; = ' 0 ' & amp& amp* p & lt='9')

data =(data & lt; & lt4)+(* p-' 0 '); /* Data & lt& lt4 is equivalent to data * 16*/

else if(* p & gt; = ' a ' & amp& amp* p & lt='f ')

data =(data & lt; & lt4)+(* p-' a '+ 10);

else if(* p & gt; = ' A ' & amp& amp* p & lt='F ')

data =(data & lt; & lt4)+(* p-' A '+ 10);

other

{

Printf("*c is not a hexadecimal character. \n ",* p);

return- 1;

}

p++;

}

Return data;

}

int main()

{

char str[ 100]= " FF ";

Long data;

gets(str);

data = str 2 num(str);

printf("str=%s\t data=%ld\n ",str,data);

getch();

Returns 0;

}