title: Most efficient way to convert 8 hex chars into a 4-uint8_t array?
body: <p>I have a <code>const char*</code>, pointing to an array of 8 characters (that may be a part of a larger string), containing a hexadecimal value. I need a function that converts those chars into an array of 4 <code>uint8_t</code>, where the two first characters in the source array will become the first element in the target array, and so on. For example, if I have this</p>
  
  <pre><code>const char* s = "FA0BD6E4";
  </code></pre>
  
  <p>I want it converted to </p>
  
  <pre><code>uint8_t i[4] = {0xFA, 0x0B, 0xD6, 0xE4};
  </code></pre>
  
  <p>Currently, I have these functions:</p>
  
  <pre><code>inline constexpr uint8_t HexChar2UInt8(char h) noexcept
  {
      return static_cast&lt;uint8_t&gt;((h &amp; 0xF) + (((h &amp; 0x40) &gt;&gt; 3) | ((h &amp; 0x40) &gt;&gt; 6)));
  }
  
  inline constexpr uint8_t HexChars2UInt8(char h0, char h1) noexcept
  {
      return (HexChar2UInt8(h0) &lt;&lt; 4) | HexChar2UInt8(h1);
  }
  
  inline constexpr std::array&lt;uint8_t, 4&gt; HexStr2UInt8(const char* in) noexcept
  {
      return {{
          HexChars2UInt8(in[0], in[1]),
          HexChars2UInt8(in[2], in[3]),
          HexChars2UInt8(in[4], in[5]),
          HexChars2UInt8(in[6], in[7])
      }};
  }
  </code></pre>
  
  <p>Here's what it will look like where I call it from:</p>
  
  <pre><code>const char* s = ...; // the source string
  std::array&lt;uint8_t, 4&gt; a; // I need to place the resulting value in this array
  a = HexStr2UInt8(s); // the function call does not have to look like this
  </code></pre>
  
  <p>What I'm wondering, is there any more efficient (and portable) way do do this? For example, is returning a <code>std::array</code> a good thing to do, or should I pass a <code>dst</code> pointer to <code>HexChars2UInt8</code>? Or are there any other way to improve my function(s)?</p>
  
  <p>The main reason I'm asking this is because I will likely need to optimize this at some point, and it will be problematic if the API (the function prototype) is changed in the future.</p>