title: char[] to hex string exercise
body: <p>Below is my current char* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?</p>
  
  <p>How can I make this faster?</p>
  
  <p>Compiled with -O3 in g++</p>
  
  <pre><code>static const char _hex2asciiU_value[256][2] =
       { {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} };
  
  std::string char_to_hex( const unsigned char* _pArray, unsigned int _len )
  {
      std::string str;
      str.resize(_len*2);
      char* pszHex = &amp;str[0];
      const unsigned char* pEnd = _pArray + _len;
  
      clock_t stick, etick;
      stick = clock();
      for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {
          pszHex[0] = _hex2asciiU_value[*pChar][0];
          pszHex[1] = _hex2asciiU_value[*pChar][1];
      }
      etick = clock();
  
      std::cout &lt;&lt; "ticks to hexify " &lt;&lt; etick - stick &lt;&lt; std::endl;
  
      return str;
  }
  </code></pre>
  
  <p><strong>Updates</strong></p>
  
  <p>Added timing code</p>
  
  <p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69126">Brian R. Bondy</a>: replace the std::string with a heap alloc'd buffer and change ofs*16 to ofs &lt;&lt; 4 - however the heap allocated buffer seems to slow it down? - result ~11ms</p>
  
  <p><a href="https://stackoverflow.com/questions/69115/#69305">Antti Sykäri</a>:replace inner loop with </p>
  
  <pre><code> int upper = *pChar &gt;&gt; 4;
   int lower = *pChar &amp; 0x0f;
   pszHex[0] = pHex[upper];
   pszHex[1] = pHex[lower];
  </code></pre>
  
  <p>result ~8ms</p>
  
  <p><a href="https://stackoverflow.com/questions/69115?sort=votes#69218">Robert</a>: replace <code>_hex2asciiU_value</code> with a full 256-entry table, sacrificing memory space but result ~7ms!</p>
  
  <p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#70254">HoyHoy</a>: Noted it was producing incorrect results</p>