Handling of conversions from and to hex

后端 未结 3 1859

I want to build a function to easily convert a string containing hex code (eg. \"0ae34e\") into a string containing the equivalent ascii values and vice versa. Do I have to cut

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-24 03:55

    The sprintf and sscanf functions can already do that for you. This code is an example that should give you an idea. Please go through the function references and the safe alternatives before you use them

    #include 
    int main()
    {
     int i;
     char str[80]={0};
     char input[80]="0x01F1";
     int output;
     /* convert a hex input to integer in string */
     printf ("Hex number: ");
     scanf ("%x",&i);
     sprintf (str,"%d",i,i);
     printf("%s\n",str);
    /* convert input in hex to integer in string */
     sscanf(input,"%x",&output);
     printf("%d\n",output);
    }
    

提交回复
热议问题