title: Converting hexadecimal to uint8_t in C++
body: <p>I am working in C++ and let's say I have the following hexadecimal as a string</p>
  
  <pre><code>string key = "F3D5";
  </code></pre>
  
  <p>how can I convert it to an array of <code>uint8_t</code>?</p>
  
  <p>Actually, I have an algorithm that generate a key of type <code>uint8_t*</code>, and I convert this key to hexadecimal using the following code : </p>
  
  <pre><code>uint8_t key = generateKey();
  vector&lt;uint8_t&gt; keyVector(begin(key), end(key));
  string hexadecimalKey= uint8_vector_to_hex_string(keyVector);
  </code></pre>
  
  <p>This is the method that convert uint8 vector to hexadecimal in string : </p>
  
  <pre><code>string uint8_vector_to_hex_string(const vector&lt;uint8_t&gt;&amp; v) {
      stringstream ss;
      ss &lt;&lt; hex &lt;&lt; setfill('0');
      vector&lt;uint8_t&gt;::const_iterator it;
  
      for (it = v.begin(); it != v.end(); it++) {
          ss &lt;&lt; setw(2) &lt;&lt; static_cast&lt;unsigned&gt;(*it);
      }
  
      return ss.str();
  }
  </code></pre>
  
  <p>And I would like to re-convert the <code>hexadecimalKey</code> to uint8_t, with the following code </p>
  
  <pre><code>uint8_t* convertedKey = hex_string_to_uint8_t(hexadecimalKey);
  </code></pre>
  
  <p>with the following method :</p>
  
  <pre><code>uint8_t* hex_string_to_uint8_t(string value) {
      size_t len = value.length();
      vector&lt;uint8_t&gt; out;
      for (size_t i = 0; i &lt; len; i += 2) {
          std::istringstream strm(value.substr(i, 2));
          uint8_t x;
          strm &gt;&gt; std::hex &gt;&gt; x;
          out.push_back(x);
      }
      return out.data();
  }
  </code></pre>
  
  <p>and whenever i do that, the <code>convertedKey</code> is not equal to <code>key</code> </p>
  
  <p>I need your help.</p>
  
  <p>Thank you, really appreciate it</p>