title: C++: How to encode a std::string into base64 without losing NUL character
body: <p>I am working on getting <a href="https://sourceforge.net/projects/harmonyhubcontrol/files/" rel="nofollow">someone else's code</a> up and running. The code is written in C++. The part that is failing is when it converts a std::string to base64:</p>
  
  <pre><code>std::string tmp = "\0";
  tmp.append(strUserName);
  tmp.append("\0");
  tmp.append(strPassword);
  tmp = base64_encode(tmp.c_str(), tmp.length());
  </code></pre>
  
  <p>where base64 is:</p>
  
  <pre><code>std::string base64_encode(char const* bytes_to_encode, unsigned int in_len) {
      std::string ret;
      int i = 0;
      int j = 0;
      unsigned char char_array_3[3];
      unsigned char char_array_4[4];
  
      while (in_len--) {
          char_array_3[i++] = *(bytes_to_encode++);
          if (i == 3) {
              char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2;
              char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4);
              char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6);
              char_array_4[3] = char_array_3[2] &amp; 0x3f;
  
              for(i = 0; (i &lt;4) ; i++)
                  ret += base64_chars[char_array_4[i]];
              i = 0;
          }
      }
  
      if (i)
      {
          for(j = i; j &lt; 3; j++)
              char_array_3[j] = '\0';
  
          char_array_4[0] = (char_array_3[0] &amp; 0xfc) &gt;&gt; 2;
          char_array_4[1] = ((char_array_3[0] &amp; 0x03) &lt;&lt; 4) + ((char_array_3[1] &amp; 0xf0) &gt;&gt; 4);
          char_array_4[2] = ((char_array_3[1] &amp; 0x0f) &lt;&lt; 2) + ((char_array_3[2] &amp; 0xc0) &gt;&gt; 6);
          char_array_4[3] = char_array_3[2] &amp; 0x3f;
  
          for (j = 0; (j &lt; i + 1); j++)
              ret += base64_chars[char_array_4[j]];
  
          while((i++ &lt; 3))
              ret += '=';
  
      }
  
      return ret;
  
  }
  </code></pre>
  
  <p>It uses the 'tmp' string to make a call to a server and it's imperative that the base64 string has the two NUL characters embedded within it (before strUserName and before strPassword). However, it seems that since the code is passing tmp as a c_str(), the NUL characters are being stripped. Is there a good solution for this? Thanks.</p>
  
  <p><strong>Update</strong> I guess I should add that the code includes "<code>#include &lt;asm/errno.h&gt;</code>" which I googled for and didn't find compatibility for macOS so I just commented it out.. Not sure if that is making things not work but I doubt it. Full disclosure.</p>