title: Convert to ASCII String from hex String in C
body: <p>I am trying to convert a hex string to its equivalent ASCII. I am given a "hex" value of a string as a string, i.e instead of "ABCD" I get "41424344". I just need to extract 41 which will be my hexvalue and recode as "ABCD". Here is what I have.</p>
  
  <pre><code>   int main(int argc, char *argv[]){
  
      char *str = "ABCD";
      unsigned int val = 0;
      int i = 0;
      int MAX = 4;
      for (i = 0; i&lt;MAX; i++){
          val = (str[i] &amp; 0xFF);
          //printf("dec val= %d\n", val);
          //printf("hex val= %02x\n", val);
      }
      val = 0;
      char *hexstr = "41424344";
      char *substr = (char*)malloc(3);
      char *ptr = hexstr;
  
      for (i = 0; i&lt;8; i++){
          strncpy(substr, ptr, 2);
          printf("substr = %s\n", substr);
          int s = atoi(substr);
          printf("s= %d\n", s);
          ptr= ptr+2;
          i = i+2;
      }
      return 0;
  
  }
  </code></pre>
  
  <p>The thing is from here on, I have to make this "s" value to be a hex value and not an int. How can this be done?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Here is what I have after your answers:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  int main(int argc, char *argv[]){
  
      char *str = "ABCD";
      unsigned int val;
      val = 0;
      int i = 0;
      int MAX = 4;
      for (i = 0; i&lt;MAX; i++){
          val = (str[i] &amp; 0xFF);
          //printf("dec val= %d\n", val);
          //printf("hex val= %02x\n", val);
      }
      val = 0;
      char *hexstr = "41424344";
      char *substr = (char*)malloc(3);
      char *ptr = hexstr;
      char *retstr = (char *)malloc(5);
      char *retptr = retstr;
  
      for (i = 0; i&lt;8; i+1){
          strncpy(substr, ptr, 2);
          printf("substr = %s\n", substr);
          int s = strtol(substr, NULL, 16);
          printf("s= %d\n", s);
          ptr= ptr+2;
          i = i+2;
          sprintf(retptr, "%c", s);
          retptr = retptr +1;
      }
      printf("retstr= %s\n", retstr);
      return 0;
  
  }
  </code></pre>