title: Signed Hexadecimal string to long int function
body: <p>I need a function to convert a 32bit or 24bit signed (in two's complement) hexadecimal string into a long int. Needs to work on both 32bit and 64bit machines (regardless of the size of long int) and work regardless of whether the machine is a two's complement machine or not.</p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <pre><code>long int hex2li (char hexStr[], int signedHex)
  {
     int bits = strlen (hexStr) * 4;
  
     char *pEnd;
     long long int result = strtoll (hexStr, &amp;pEnd, 16);
  
     if (pEnd[0] == '\0')
     {
        if (signedHex)
        {
           if (result &gt;= (1LL &lt;&lt; (bits - 1))) result -= (1LL &lt;&lt; bits);
        }
  
        return (long int) result;
     }
  
     return LONG_MIN;
  }
  </code></pre>