title: How to convert a string to base64 encoding using byte array in JavaScript?
body: <p>I have the below .NET code to convert a string to Base64 encoding by first converting it to byte array. I tried different answers on Stack Overflow to convert the string in byte array and then use btoa() function for base64 encoding in JavaScript. But, I'm not getting the exact encoded value as shared below.</p>
  
  <p>For string value,</p>
  
  <blockquote>
    <p>BBFDC43D-4890-4558-BB89-50D802014A97</p>
  </blockquote>
  
  <p>I need Base64 encoding as,</p>
  
  <blockquote>
    <p>PcT9u5BIWEW7iVDYAgFKlw==</p>
  </blockquote>
  
  <p>.NET code:</p>
  
  <pre><code>String str = "BBFDC43D-4890-4558-BB89-50D802014A97"
  Guid guid = new Guid(str);
  Console.WriteLine(guid);    // bbfdc43d-4890-4558-bb89-50d802014a97
  Byte[] bytes = guid.ToByteArray();
  Console.WriteLine(bytes);   // System.Byte[]
  String s = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
  Console.WriteLine(s);   // PcT9u5BIWEW7iVDYAgFKlw==
  </code></pre>
  
  <p>Currently, I tried with the below code, which is not producing the desired result:</p>
  
  <pre><code>function strToUtf8Bytes(str) {
    const utf8 = [];
    for (let ii = 0; ii &lt; str.length; ii++) {
      let charCode = str.charCodeAt(ii);
      if (charCode &lt; 0x80) utf8.push(charCode);
      else if (charCode &lt; 0x800) {
        utf8.push(0xc0 | (charCode &gt;&gt; 6), 0x80 | (charCode &amp; 0x3f));
      } else if (charCode &lt; 0xd800 || charCode &gt;= 0xe000) {
        utf8.push(0xe0 | (charCode &gt;&gt; 12), 0x80 | ((charCode &gt;&gt; 6) &amp; 0x3f), 0x80 | (charCode &amp; 0x3f));
      } else {
        ii++;
        // Surrogate pair:
        // UTF-16 encodes 0x10000-0x10FFFF by subtracting 0x10000 and
        // splitting the 20 bits of 0x0-0xFFFFF into two halves
        charCode = 0x10000 + (((charCode &amp; 0x3ff) &lt;&lt; 10) | (str.charCodeAt(ii) &amp; 0x3ff));
        utf8.push(
          0xf0 | (charCode &gt;&gt; 18),
          0x80 | ((charCode &gt;&gt; 12) &amp; 0x3f),
          0x80 | ((charCode &gt;&gt; 6) &amp; 0x3f),
          0x80 | (charCode &amp; 0x3f),
        );
      }
    }
    return utf8;
  }
  
  const str = "BBFDC43D-4890-4558-BB89-50D802014A97";
  const strByteArr = strToUtf8Bytes(str);
  const strBase64 = btoa(strByteArr);
  // NjYsNjYsNzAsNjgsNjcsNTIsNTEsNjgsNDUsNTIsNTYsNTcsNDgsNDUsNTIsNTMsNTMsNTYsNDUsNjYsNjYsNTYsNTcsNDUsNTMsNDgsNjgsNTYsNDgsNTAsNDgsNDksNTIsNjUsNTcsNTU=
  </code></pre>