<p>In C, what is the most efficient way to convert a string of hex digits into a binary <code>unsigned int</code> or <code>unsigned long</code>?</p>

<p>For example, if I have <code>0xFFFFFFFE</code>, I want an <code>int</code> with the base10 value <code>4294967294</code>.</p>

[{'answer_id': 10327, 'author': 'Patrick', 'author_id': 429, 'author_profile': 'https://Stackoverflow.com/users/429', 'pm_score': 6, 'selected': True, 'text': '<p>You want <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/strtol.html" rel="noreferrer"><code>strtol</code></a> or <a href="http://en.cppreference.com/w/c/string/byte/strtoul" rel="noreferrer"><code>strtoul</code></a>.  See also the <a href="http://man7.org/linux/man-pages/man3/strtoul.3.html" rel="noreferrer">Unix man page</a></p>\n'}, {'answer_id': 10331, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 5, 'selected': False, 'text': '<p>Try this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main()\n{\n    char s[] = "fffffffe";\n    int x;\n    sscanf(s, "%x", &amp;x);\n    printf("%u\\n", x);\n}\n</code></pre>\n'}, {'answer_id': 10521, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 2, 'selected': False, 'text': '<p>@Eric</p>\n\n<blockquote>\n  <p>Why is a code solution that works getting voted down? Sure, it\'s ugly and might not be the fastest way to do it, but it\'s more instructive that saying "strtol" or "sscanf". If you try it yourself you will learn something about how things happen under the hood.</p>\n</blockquote>\n\n<p>I don\'t really think your solution should have been voted down, but my guess as to why it\'s happening is because it\'s less practical.  The idea with voting is that the "best" answer will float to the top, and while your answer might be more instructive about what happens under the hood (or a way it might happen), it\'s definitely not the best way to parse hex numbers in a production system.</p>\n\n<p>Again, I don\'t think there\'s anything wrong with your answer from an educational standpoint, and I certainly wouldn\'t (and didn\'t) vote it down.  Don\'t get discouraged and stop posting just because some people didn\'t like one of your answers.  It happens.</p>\n\n<p>I doubt my answer makes you feel any better about yours being voted down, but I know it\'s especially not fun when you ask why something\'s being voted down and <a href="https://stackoverflow.com/questions/7430/suggestion-link-to-feature-requests-on-uservoice#7457">no one answers</a>.</p>\n'}, {'answer_id': 10552, 'author': 'Derek Park', 'author_id': 872, 'author_profile': 'https://Stackoverflow.com/users/872', 'pm_score': 2, 'selected': False, 'text': '<p>@Eric</p>\n\n<blockquote>\n  <p>I was actually hoping to see a C wizard post something really cool, sort of like what I did but less verbose, while still doing it "manually".</p>\n</blockquote>\n\n<p>Well, I\'m no C guru, but here\'s what I came up with:</p>\n\n<pre><code>unsigned int parseHex(const char * str)\n{\n    unsigned int val = 0;\n    char c;\n\n    while(c = *str++)\n    {\n        val &lt;&lt;= 4;\n\n        if (c &gt;= \'0\' &amp;&amp; c &lt;= \'9\')\n        {\n            val += c &amp; 0x0F;\n            continue;\n        }\n\n        c &amp;= 0xDF;\n        if (c &gt;= \'A\' &amp;&amp; c &lt;= \'F\')\n        {\n            val += (c &amp; 0x07) + 9;\n            continue;\n        }\n\n        errno = EINVAL;\n        return 0;\n    }\n\n    return val;\n}\n</code></pre>\n\n<p>I originally had more bitmasking going on instead of comparisons, but I seriously doubt bitmasking is any faster than comparison on modern hardware.</p>\n'}, {'answer_id': 11111, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>For larger Hex strings like in the example I needed to use <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul.html" rel="nofollow noreferrer">strtoul</a>.</p>\n'}, {'answer_id': 24158, 'author': 'itj', 'author_id': 888, 'author_profile': 'https://Stackoverflow.com/users/888', 'pm_score': 1, 'selected': False, 'text': "<blockquote>\n  <p>Why is a code solution that works\n  getting voted down? Sure, it's ugly\n  ...</p>\n</blockquote>\n\n<p>Perhaps because as well as being ugly it isn't educational and <strong>doesn't</strong> work.  Also, I suspect that like me, most people don't have the power to edit at present (and judging by the rank needed - never will).</p>\n\n<p>The use of an array can be good for efficiency, but that's not mentioned in this code.\nIt also takes no account of upper and lower case so it does not work for the example supplied in the question. FFFFFFFE </p>\n"}, {'answer_id': 130552, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>If you don't have the stdlib then you have to do it manually.</p>\n\n<pre><code>unsigned long hex2int(char *a, unsigned int len)\n{\n    int i;\n    unsigned long val = 0;\n\n    for(i=0;i&lt;len;i++)\n       if(a[i] &lt;= 57)\n        val += (a[i]-48)*(1&lt;&lt;(4*(len-1-i)));\n       else\n        val += (a[i]-55)*(1&lt;&lt;(4*(len-1-i)));\n\n    return val;\n}\n</code></pre>\n\n<p>Note: This code assumes uppercase A-F.  It does not work if len is beyond your longest integer 32 or 64bits, and there is no error trapping for illegal hex characters.</p>\n"}, {'answer_id': 4054173, 'author': 'Adam B.', 'author_id': 491552, 'author_profile': 'https://Stackoverflow.com/users/491552', 'pm_score': -1, 'selected': False, 'text': '<p>This currently only works with lower case but its super easy to make it work with both.</p>\n\n<pre><code>cout &lt;&lt; "\\nEnter a hexadecimal number: ";\ncin &gt;&gt; hexNumber;\norighex = hexNumber;\n\nstrlength = hexNumber.length();\n\nfor (i=0;i&lt;strlength;i++)\n{\n    hexa = hexNumber.substr(i,1);\n    if ((hexa&gt;="0") &amp;&amp; (hexa&lt;="9"))\n    {\n        //cout &lt;&lt; "This is a numerical value.\\n";\n    }\n    else\n    {\n        //cout &lt;&lt; "This is a alpabetical value.\\n";\n        if (hexa=="a"){hexa="10";}\n        else if (hexa=="b"){hexa="11";}\n        else if (hexa=="c"){hexa="12";}\n        else if (hexa=="d"){hexa="13";}\n        else if (hexa=="e"){hexa="14";}\n        else if (hexa=="f"){hexa="15";}\n        else{cout &lt;&lt; "INVALID ENTRY! ANSWER WONT BE CORRECT\\n";}\n    }\n    //convert from string to integer\n\n    hx = atoi(hexa.c_str());\n    finalhex = finalhex + (hx*pow(16.0,strlength-i-1));\n}\ncout &lt;&lt; "The hexadecimal number: " &lt;&lt; orighex &lt;&lt; " is " &lt;&lt; finalhex &lt;&lt; " in decimal.\\n";\n</code></pre>\n'}, {'answer_id': 4054250, 'author': 'AnT stands with Russia', 'author_id': 187690, 'author_profile': 'https://Stackoverflow.com/users/187690', 'pm_score': 3, 'selected': False, 'text': '<p>As if often happens, your question suffers from a serious terminological error/ambiguity. In common speech it usually doesn\'t matter, but in the context of this specific problem it is critically important. </p>\n\n<p>You see, there\'s no such thing as "hex value" and "decimal value" (or "hex number" and "decimal number"). "Hex" and "decimal" are properties of <em>representations</em> of values. Meanwhile, values (or numbers) by themselves have no representation, so they can\'t be "hex" or "decimal". For example, <code>0xF</code> and <code>15</code> in C syntax are two different <em>representations</em> of <em>the same number</em>.</p>\n\n<p>I would guess that your question, the way it is stated, suggests that you need to convert ASCII hex representation of a value (i.e. a string) into a ASCII decimal representation of a value (another string). One way to do that is to use an integer representation as an intermediate one: first, convert ASCII hex representation to an integer of sufficient size (using functions from <code>strto...</code> group, like <code>strtol</code>), then convert the integer into the ASCII decimal representation (using <code>sprintf</code>).</p>\n\n<p>If that\'s not what you need to do, then you have to clarify your question, since it is impossible to figure it out from the way your question is formulated.</p>\n'}, {'answer_id': 4484238, 'author': 'MBANZABUGABO Jean Bapitiste', 'author_id': 547846, 'author_profile': 'https://Stackoverflow.com/users/547846', 'pm_score': 0, 'selected': False, 'text': '<p>Try this to Convert from Decimal to Hex</p>\n\n<pre><code>    #include&lt;stdio.h&gt;\n    #include&lt;conio.h&gt;\n\n    int main(void)\n    {\n      int count=0,digit,n,i=0;\n      int hex[5];\n      clrscr();\n      printf("enter a number   ");\n      scanf("%d",&amp;n);\n\n      if(n&lt;10)\n      {\n          printf("%d",n);\n      }\n\n      switch(n)\n      {\n          case 10:\n              printf("A");\n            break;\n          case 11:\n              printf("B");\n            break;\n          case 12:\n              printf("B");\n            break;\n          case 13:\n              printf("C");\n            break;\n          case 14:\n              printf("D");\n            break;\n          case 15:\n              printf("E");\n            break;\n          case 16:\n              printf("F");\n            break;\n          default:;\n       }\n\n       while(n&gt;16)\n       {\n          digit=n%16;\n          hex[i]=digit;\n          i++;\n          count++;\n          n=n/16;\n       }\n\n       hex[i]=n;\n\n       for(i=count;i&gt;=0;i--)\n       {\n          switch(hex[i])\n          {\n             case 10:\n                 printf("A");\n               break;\n             case 11:\n                 printf("B");\n               break;\n             case 12:\n                 printf("C");\n               break;\n             case  13:\n                 printf("D");\n               break;\n             case 14:\n                 printf("E");\n               break;\n             case 15:\n                 printf("F");\n               break;\n             default:\n                 printf("%d",hex[i]);\n          }\n    }\n\n    getch();\n\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 8282059, 'author': 'rishabh kedia', 'author_id': 1067351, 'author_profile': 'https://Stackoverflow.com/users/1067351', 'pm_score': 2, 'selected': False, 'text': '<p>Hexadecimal to decimal. Don\'t run it on online compilers, because it won\'t work.</p>\n\n<pre><code>#include&lt;stdio.h&gt;\nvoid main()\n{\n    unsigned int i;\n    scanf("%x",&amp;i);\n    printf("%d",i);\n}\n</code></pre>\n'}, {'answer_id': 11068850, 'author': 'Orwellophile', 'author_id': 912236, 'author_profile': 'https://Stackoverflow.com/users/912236', 'pm_score': 5, 'selected': False, 'text': '<p>Edit: <strong>Now compatible with MSVC, C++ and non-GNU compilers (see end).</strong></p>\n\n<p>The question was "most efficient way."  The OP doesn\'t specify platform, he could be compiling for a RISC based ATMEL chip with 256 bytes of flash storage for his code.</p>\n\n<p>For the record, and for those (like me), who appreciate the difference between "the easiest way" and the "most efficient way", and who enjoy learning... </p>\n\n<pre><code>static const long hextable[] = {\n   [0 ... 255] = -1, // bit aligned access into this table is considerably\n   [\'0\'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // faster for most modern processors,\n   [\'A\'] = 10, 11, 12, 13, 14, 15,       // for the space conscious, reduce to\n   [\'a\'] = 10, 11, 12, 13, 14, 15        // signed char.\n};\n\n/** \n * @brief convert a hexidecimal string to a signed long\n * will not produce or process negative numbers except \n * to signal error.\n * \n * @param hex without decoration, case insensitive. \n * \n * @return -1 on error, or result (max (sizeof(long)*8)-1 bits)\n */\nlong hexdec(unsigned const char *hex) {\n   long ret = 0; \n   while (*hex &amp;&amp; ret &gt;= 0) {\n      ret = (ret &lt;&lt; 4) | hextable[*hex++];\n   }\n   return ret; \n}\n</code></pre>\n\n<p>It requires no external libraries, and it should be blindingly fast.   It handles uppercase, lowercase, invalid characters, odd-sized hex input (eg: 0xfff), and the maximum size is limited only by the compiler.</p>\n\n<p><strong>For non-GCC or C++ compilers or compilers that will not accept the fancy hextable declaration.</strong></p>\n\n<p>Replace the first statement with this (longer, but more conforming) version:</p>\n\n<pre><code>static const long hextable[] = { \n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,\n    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1\n};\n</code></pre>\n'}, {'answer_id': 11809169, 'author': 'Sunday Efeh', 'author_id': 1576168, 'author_profile': 'https://Stackoverflow.com/users/1576168', 'pm_score': 1, 'selected': False, 'text': '<pre><code>#include "math.h"\n#include "stdio.h"\n///////////////////////////////////////////////////////////////\n//  The bits arg represents the bit say:8,16,32...                                                                                                              \n/////////////////////////////////////////////////////////////\nvolatile long Hex_To_Int(long Hex,char bits)\n{\n    long Hex_2_Int;\n    char byte;\n    Hex_2_Int=0;\n\n    for(byte=0;byte&lt;bits;byte++)\n    {\n        if(Hex&amp;(0x0001&lt;&lt;byte))\n            Hex_2_Int+=1*(pow(2,byte));\n        else\n            Hex_2_Int+=0*(pow(2,byte));\n    }\n\n    return Hex_2_Int;\n}\n///////////////////////////////////////////////////////////////\n//                                                                                                                  \n/////////////////////////////////////////////////////////////\n\nvoid main (void)\n{\n    int Dec;   \n    char Hex=0xFA;\n    Dec= Hex_To_Int(Hex,8);  //convert an 8-bis hexadecimal value to a number in base 10\n    printf("the number is %d",Dec);\n}\n</code></pre>\n'}, {'answer_id': 39052834, 'author': 'radhoo', 'author_id': 486907, 'author_profile': 'https://Stackoverflow.com/users/486907', 'pm_score': 3, 'selected': False, 'text': '<p>For AVR Microcontrollers I wrote the following function, including relevant comments to make it easy to understand:</p>\n\n<pre><code>/**\n * hex2int\n * take a hex string and convert it to a 32bit number (max 8 hex digits)\n */\nuint32_t hex2int(char *hex) {\n    uint32_t val = 0;\n    while (*hex) {\n        // get current character then increment\n        char byte = *hex++; \n        // transform hex character to the 4bit equivalent number, using the ascii table indexes\n        if (byte &gt;= \'0\' &amp;&amp; byte &lt;= \'9\') byte = byte - \'0\';\n        else if (byte &gt;= \'a\' &amp;&amp; byte &lt;=\'f\') byte = byte - \'a\' + 10;\n        else if (byte &gt;= \'A\' &amp;&amp; byte &lt;=\'F\') byte = byte - \'A\' + 10;    \n        // shift 4 to make space for new digit, and add the 4 bits of the new digit \n        val = (val &lt;&lt; 4) | (byte &amp; 0xF);\n    }\n    return val;\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>char *z ="82ABC1EF";\nuint32_t x = hex2int(z);\nprintf("Number is [%X]\\n", x);\n</code></pre>\n\n<p>Will output:\n<a href="https://i.stack.imgur.com/IjCX0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IjCX0.png" alt="enter image description here"></a></p>\n'}, {'answer_id': 45190525, 'author': 'Cactus1549', 'author_id': 7152318, 'author_profile': 'https://Stackoverflow.com/users/7152318', 'pm_score': -1, 'selected': False, 'text': '<p>In C you can convert a hexadecimal number to decimal in many ways. One way is to cast the hexadecimal number to an integer. I personally found this to be simple and small.</p>\n\n<p>Here is an sample code for converting a Hexadecimal number to a Decimal number with the help of casting.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(){\n    unsigned char Hexadecimal = 0x6D;   //example hex number\n    int Decimal = 0;    //decimal number initialized to 0\n\n\n        Decimal = (int) Hexadecimal;  //conversion\n\n    printf("The decimal number is %d\\n", Decimal);  //output\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 58253411, 'author': 'Simon', 'author_id': 5951263, 'author_profile': 'https://Stackoverflow.com/users/5951263', 'pm_score': 2, 'selected': False, 'text': '<p>As written before, the efficiency basically depends on what one is optimizing for.</p>\n\n<p>When optiming for lines of code, or just working in environment without fully-equipped standard library one quick and dirty option could be:</p>\n\n<pre><code>// makes a number from two ascii hexa characters\nint ahex2int(char a, char b){\n\n    a = (a &lt;= \'9\') ? a - \'0\' : (a &amp; 0x7) + 9;\n    b = (b &lt;= \'9\') ? b - \'0\' : (b &amp; 0x7) + 9;\n\n    return (a &lt;&lt; 4) + b;\n}\n</code></pre>\n\n<p>... more in similar thread here: <a href="https://stackoverflow.com/a/58253380/5951263">https://stackoverflow.com/a/58253380/5951263</a></p>\n'}]
['https://Stackoverflow.com/questions/10324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']