title: Convert Hex to Binary in C
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8197838/convert-a-long-hex-string-in-to-int-array-with-sscanf">Convert a long hex string in to int array with sscanf</a>  </p>
  </blockquote>
  
  
  
  <p>I have seen some topics on this before, but most solutions are in Python (curse you for being so easy!).</p>
  
  <p>Is there an easy way to do this in C? This is what my solution needs to be in. I know it's not complicated conceptually, but I am horrendous with C string manipulation and address handling.</p>
  
  <p>Thanks for the help, guys!</p>
  
  <p>----------EDIT-------------</p>
  
  <p>Okay, so I solved that problem, and I have another question (I didn't want to open up a new thread!). Below is my modification to the given code, with the function call and the output.</p>
  
  <pre><code>void htoi(const char *ptr, char *binAddr) {
  char value[32] = "";
  char ch = *ptr;
  int i;
  const char* quads[] = {"0000", "0001", "0010", "0011", "0100", "0101",
                       "0110", "0111", "1000", "1001", "1010", "1011",
                       "1100", "1101", "1110", "1111"};
  
  while (ch == ' ' || ch == '\t')
      ch = *(++ptr);
  
  for (i = 0; i &lt; 8; i++) {
      if (ch &gt;= '0' &amp;&amp; ch &lt;= '9')
          strncat(value, quads[ch - '0'], 4);
      if (ch &gt;= 'A' &amp;&amp; ch &lt;= 'F')
          strncat(value, quads[10 + ch - 'A'], 4);
      if (ch &gt;= 'a' &amp;&amp; ch &lt;= 'f')
          strncat(value, quads[10 + ch - 'a'], 4);
  
      ch = *(++ptr);
      printf("%s\n", value);
  }
  
  *binAddr = *value;
  }
  </code></pre>
  
  <p>Here is my function call:</p>
  
  <pre><code>char line[11], hexAddr[8], binAddr[32];
  htoi(hexAddr, binAddr);
  printf("%s\n", binAddr);
  </code></pre>
  
  <p>Here is the output (when input with 001133c0):</p>
  
  <p>0000</p>
  
  <p>00000000</p>
  
  <p>000000000001</p>
  
  <p>0000000000010001</p>
  
  <p>00000000000100010011</p>
  
  <p>000000000001000100110011</p>
  
  <p>0000000000010001001100111100</p>
  
  <p>00000000000100010011001111000000</p>
  
  <p>0���</p>
  
  <p>The last line (with the special characters) is the printf(binAddr) in the main function above. It is clear from the printf statements inside the function that the binary code is being constructed correctly.</p>
  
  <p>Once again, this comes down to me not being worth anything with address manipulation. What am I doing wrong?</p>