How to convert a string to base64 encoding using byte array in JavaScript?How can you encode a string to Base64 in JavaScript?ArrayBuffer to base64 encoded stringHow to convert a String to BytearrayHow do JavaScript closures work?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?Encode URL in JavaScript?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string?How to check whether a string contains a substring in JavaScript?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?

Sometimes you are this word with three vowels

How to repair basic cable/wire issue for household appliances

Is it OK to accept a job opportunity while planning on not taking it?

Sci-fi short story: plants attracting spaceship and using them as a agents of pollination between two planets

How can the artificial womb be made affordable for the common people?

Short story about a group of sci-fi writers sitting around discussing their profession

How important is a good quality camera for good photography?

Why can't a country print its own money to spend it only abroad?

Why must API keys be kept private?

Impact of throwing away fruit waste on a peak > 3200 m above a glacier

"It is what it is" in French

Other than a swing wing, what types of variable geometry have flown?

Issue with ContourPlot

How may I shorten this shell script?

How can I tell if there was a power cut when I was out?

ExactlyOne extension method

Extrapolation v. Interpolation

Using "Kollege" as "university friend"?

What would be the side effects on the life of a person becoming indestructible?

Alternative methods for solving a system of one linear one non linear simultaneous equations

Are gangsters hired to attack people at a train station classified as a terrorist attack?

Can I pay with HKD in Macau or Shenzhen?

What kind of world would drive brains to evolve high-throughput sensory?

Why is chess failing to attract big name sponsors?



How to convert a string to base64 encoding using byte array in JavaScript?


How can you encode a string to Base64 in JavaScript?ArrayBuffer to base64 encoded stringHow to convert a String to BytearrayHow do JavaScript closures work?How do I remove a property from a JavaScript object?How do I check if an array includes an object in JavaScript?Encode URL in JavaScript?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string?How to check whether a string contains a substring in JavaScript?Loop through an array in JavaScriptHow do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















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.



For string value,




BBFDC43D-4890-4558-BB89-50D802014A97




I need Base64 encoding as,




PcT9u5BIWEW7iVDYAgFKlw==




.NET 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==


Currently, I tried with the below code, which is not producing the desired result:



function strToUtf8Bytes(str) 
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) charCode >= 0xe000) (charCode >> 12), 0x80 else (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0

return utf8;


const str = "BBFDC43D-4890-4558-BB89-50D802014A97";
const strByteArr = strToUtf8Bytes(str);
const strBase64 = btoa(strByteArr);
// NjYsNjYsNzAsNjgsNjcsNTIsNTEsNjgsNDUsNTIsNTYsNTcsNDgsNDUsNTIsNTMsNTMsNTYsNDUsNjYsNjYsNTYsNTcsNDUsNTMsNDgsNjgsNTYsNDgsNTAsNDgsNDksNTIsNjUsNTcsNTU=









share|improve this question
























  • Could you also provide the JS code you use?

    – Patrick
    Mar 26 at 11:40











  • maybe dupplicate from: stackoverflow.com/questions/246801/…

    – LeBigCat
    Mar 26 at 11:45











  • This is not the duplicate of that question because I'm using btoa() to encode but I'm concerned about the byte array here.

    – Himanshu Aggarwal
    Mar 26 at 11:51






  • 1





    Are you sure that PcT9u5BIWEW7iVDYAgFKlw== is the base64 representation of the string BBFDC43D-4890-4558-BB89-50D802014A97

    – John
    Mar 26 at 11:51






  • 1





    You should post your javascript code. And again, as I said before, your code is not converting that string to base64, it's taking that string as a bunch of hex values, converting it to base 10, and then encoding the resulting byte array to base 64

    – Magnetron
    Mar 26 at 11:59

















0















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.



For string value,




BBFDC43D-4890-4558-BB89-50D802014A97




I need Base64 encoding as,




PcT9u5BIWEW7iVDYAgFKlw==




.NET 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==


Currently, I tried with the below code, which is not producing the desired result:



function strToUtf8Bytes(str) 
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) charCode >= 0xe000) (charCode >> 12), 0x80 else (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0

return utf8;


const str = "BBFDC43D-4890-4558-BB89-50D802014A97";
const strByteArr = strToUtf8Bytes(str);
const strBase64 = btoa(strByteArr);
// NjYsNjYsNzAsNjgsNjcsNTIsNTEsNjgsNDUsNTIsNTYsNTcsNDgsNDUsNTIsNTMsNTMsNTYsNDUsNjYsNjYsNTYsNTcsNDUsNTMsNDgsNjgsNTYsNDgsNTAsNDgsNDksNTIsNjUsNTcsNTU=









share|improve this question
























  • Could you also provide the JS code you use?

    – Patrick
    Mar 26 at 11:40











  • maybe dupplicate from: stackoverflow.com/questions/246801/…

    – LeBigCat
    Mar 26 at 11:45











  • This is not the duplicate of that question because I'm using btoa() to encode but I'm concerned about the byte array here.

    – Himanshu Aggarwal
    Mar 26 at 11:51






  • 1





    Are you sure that PcT9u5BIWEW7iVDYAgFKlw== is the base64 representation of the string BBFDC43D-4890-4558-BB89-50D802014A97

    – John
    Mar 26 at 11:51






  • 1





    You should post your javascript code. And again, as I said before, your code is not converting that string to base64, it's taking that string as a bunch of hex values, converting it to base 10, and then encoding the resulting byte array to base 64

    – Magnetron
    Mar 26 at 11:59













0












0








0








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.



For string value,




BBFDC43D-4890-4558-BB89-50D802014A97




I need Base64 encoding as,




PcT9u5BIWEW7iVDYAgFKlw==




.NET 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==


Currently, I tried with the below code, which is not producing the desired result:



function strToUtf8Bytes(str) 
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) charCode >= 0xe000) (charCode >> 12), 0x80 else (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0

return utf8;


const str = "BBFDC43D-4890-4558-BB89-50D802014A97";
const strByteArr = strToUtf8Bytes(str);
const strBase64 = btoa(strByteArr);
// NjYsNjYsNzAsNjgsNjcsNTIsNTEsNjgsNDUsNTIsNTYsNTcsNDgsNDUsNTIsNTMsNTMsNTYsNDUsNjYsNjYsNTYsNTcsNDUsNTMsNDgsNjgsNTYsNDgsNTAsNDgsNDksNTIsNjUsNTcsNTU=









share|improve this question
















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.



For string value,




BBFDC43D-4890-4558-BB89-50D802014A97




I need Base64 encoding as,




PcT9u5BIWEW7iVDYAgFKlw==




.NET 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==


Currently, I tried with the below code, which is not producing the desired result:



function strToUtf8Bytes(str) 
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) charCode >= 0xe000) (charCode >> 12), 0x80 else (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0

return utf8;


const str = "BBFDC43D-4890-4558-BB89-50D802014A97";
const strByteArr = strToUtf8Bytes(str);
const strBase64 = btoa(strByteArr);
// NjYsNjYsNzAsNjgsNjcsNTIsNTEsNjgsNDUsNTIsNTYsNTcsNDgsNDUsNTIsNTMsNTMsNTYsNDUsNjYsNjYsNTYsNTcsNDUsNTMsNDgsNjgsNTYsNDgsNTAsNDgsNDksNTIsNjUsNTcsNTU=






javascript c# arrays .net encoding






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 12:11







Himanshu Aggarwal

















asked Mar 26 at 11:40









Himanshu AggarwalHimanshu Aggarwal

1,1331 gold badge17 silver badges30 bronze badges




1,1331 gold badge17 silver badges30 bronze badges












  • Could you also provide the JS code you use?

    – Patrick
    Mar 26 at 11:40











  • maybe dupplicate from: stackoverflow.com/questions/246801/…

    – LeBigCat
    Mar 26 at 11:45











  • This is not the duplicate of that question because I'm using btoa() to encode but I'm concerned about the byte array here.

    – Himanshu Aggarwal
    Mar 26 at 11:51






  • 1





    Are you sure that PcT9u5BIWEW7iVDYAgFKlw== is the base64 representation of the string BBFDC43D-4890-4558-BB89-50D802014A97

    – John
    Mar 26 at 11:51






  • 1





    You should post your javascript code. And again, as I said before, your code is not converting that string to base64, it's taking that string as a bunch of hex values, converting it to base 10, and then encoding the resulting byte array to base 64

    – Magnetron
    Mar 26 at 11:59

















  • Could you also provide the JS code you use?

    – Patrick
    Mar 26 at 11:40











  • maybe dupplicate from: stackoverflow.com/questions/246801/…

    – LeBigCat
    Mar 26 at 11:45











  • This is not the duplicate of that question because I'm using btoa() to encode but I'm concerned about the byte array here.

    – Himanshu Aggarwal
    Mar 26 at 11:51






  • 1





    Are you sure that PcT9u5BIWEW7iVDYAgFKlw== is the base64 representation of the string BBFDC43D-4890-4558-BB89-50D802014A97

    – John
    Mar 26 at 11:51






  • 1





    You should post your javascript code. And again, as I said before, your code is not converting that string to base64, it's taking that string as a bunch of hex values, converting it to base 10, and then encoding the resulting byte array to base 64

    – Magnetron
    Mar 26 at 11:59
















Could you also provide the JS code you use?

– Patrick
Mar 26 at 11:40





Could you also provide the JS code you use?

– Patrick
Mar 26 at 11:40













maybe dupplicate from: stackoverflow.com/questions/246801/…

– LeBigCat
Mar 26 at 11:45





maybe dupplicate from: stackoverflow.com/questions/246801/…

– LeBigCat
Mar 26 at 11:45













This is not the duplicate of that question because I'm using btoa() to encode but I'm concerned about the byte array here.

– Himanshu Aggarwal
Mar 26 at 11:51





This is not the duplicate of that question because I'm using btoa() to encode but I'm concerned about the byte array here.

– Himanshu Aggarwal
Mar 26 at 11:51




1




1





Are you sure that PcT9u5BIWEW7iVDYAgFKlw== is the base64 representation of the string BBFDC43D-4890-4558-BB89-50D802014A97

– John
Mar 26 at 11:51





Are you sure that PcT9u5BIWEW7iVDYAgFKlw== is the base64 representation of the string BBFDC43D-4890-4558-BB89-50D802014A97

– John
Mar 26 at 11:51




1




1





You should post your javascript code. And again, as I said before, your code is not converting that string to base64, it's taking that string as a bunch of hex values, converting it to base 10, and then encoding the resulting byte array to base 64

– Magnetron
Mar 26 at 11:59





You should post your javascript code. And again, as I said before, your code is not converting that string to base64, it's taking that string as a bunch of hex values, converting it to base 10, and then encoding the resulting byte array to base 64

– Magnetron
Mar 26 at 11:59












3 Answers
3






active

oldest

votes


















1














Your problem is caused by the following:




  • btoa() is using ASCII encoding


  • guid.ToByteArray(); does not use ASCII encoding

If you modify your C# code like this:



String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
//Guid guid = new Guid(str);
//Console.WriteLine(guid);
// bbfdc43d-4890-4558-bb89-50d802014a97
//Byte[] bytes = guid.ToByteArray();
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
//Console.WriteLine(bytes); // System.Byte[]
String s = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
Console.WriteLine(s);


You will get the following output:



QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


Which will be the same string as the one returned from the btoa() function:



var rawString = "BBFDC43D-4890-4558-BB89-50D802014A97";
var b64encoded = btoa(rawString);
console.log(b64encoded);


Output:



QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


UPDATE - Since you can't modify the C# code



You should adapt your Javascript code by combining Piotr's answer and this SO answer



function guidToBytes(guid) 
var bytes = [];
guid.split('-').map((number, index) =>
var bytesInChar = index < 3 ? number.match(/.1,2/g).reverse() : number.match(/.1,2/g);
bytesInChar.map((byte) => bytes.push(parseInt(byte, 16)); )
);
return bytes;


function arrayBufferToBase64(buffer)
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++)
binary += String.fromCharCode(bytes[i]);

return btoa(binary);


var str = "BBFDC43D-4890-4558-BB89-50D802014A97";
var guidBytes = guidToBytes(str);
var b64encoded = arrayBufferToBase64(guidBytes);
console.log(b64encoded);


Output:



PcT9u5BIWEW7iVDYAgFKlw==





share|improve this answer

























  • ASCII or UTF8 will make no difference here, since until codepoint 127 they are identical.

    – Sefe
    Mar 26 at 14:00











  • @marko I can't change the .NET code as it is a legacy code. I only have to replicate that in JS.

    – Himanshu Aggarwal
    Mar 26 at 14:05











  • @HimanshuAggarwal I just updated the answer with the Javascript modifications you need to make.

    – Marko Papic
    Mar 26 at 15:18











  • Awesome, @MarkoPapic. Thanks a lot for your valuable inputs. :)

    – Himanshu Aggarwal
    Mar 27 at 6:52


















1














The problem with your code is representation of Guid. In C# code you are converting "BBFDC43D-4890-4558-BB89-50D802014A97" into UUID which is a 128-bit number. In JavaScript code, you are doing something else. You iterate through the string and calculate a byte array of a string. They are simply not equal.
Now you have to options



  1. Implement proper guid conversion in JS (this may help: https://gist.github.com/daboxu/4f1dd0a254326ac2361f8e78f89e97ae)

  2. In C# calculate byte array in the same way as in JS





share|improve this answer






























    0














    Your string is a hexadecimal value, which you use to create a GUID. Then you convert the GUID into a byte array with:



    Byte[] bytes = guid.ToByteArray();


    The GUID is a 16-byte value which can be represented as a hexadecimal value. When you convert this GUID into a byte array, you will get the 16 bytes of the value, not the byte representation of the hexadecimal value.



    In the provided JavaScript function you are doing something else: You are converting the string directly to a byte array.



    In C# you do the equivalent with an Encoding:



    String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
    Byte[] bytes = Encoding.UTF8.GetBytes(str);





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55356285%2fhow-to-convert-a-string-to-base64-encoding-using-byte-array-in-javascript%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Your problem is caused by the following:




      • btoa() is using ASCII encoding


      • guid.ToByteArray(); does not use ASCII encoding

      If you modify your C# code like this:



      String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      //Guid guid = new Guid(str);
      //Console.WriteLine(guid);
      // bbfdc43d-4890-4558-bb89-50d802014a97
      //Byte[] bytes = guid.ToByteArray();
      byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
      //Console.WriteLine(bytes); // System.Byte[]
      String s = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
      Console.WriteLine(s);


      You will get the following output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      Which will be the same string as the one returned from the btoa() function:



      var rawString = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var b64encoded = btoa(rawString);
      console.log(b64encoded);


      Output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      UPDATE - Since you can't modify the C# code



      You should adapt your Javascript code by combining Piotr's answer and this SO answer



      function guidToBytes(guid) 
      var bytes = [];
      guid.split('-').map((number, index) =>
      var bytesInChar = index < 3 ? number.match(/.1,2/g).reverse() : number.match(/.1,2/g);
      bytesInChar.map((byte) => bytes.push(parseInt(byte, 16)); )
      );
      return bytes;


      function arrayBufferToBase64(buffer)
      var binary = '';
      var bytes = new Uint8Array(buffer);
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++)
      binary += String.fromCharCode(bytes[i]);

      return btoa(binary);


      var str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var guidBytes = guidToBytes(str);
      var b64encoded = arrayBufferToBase64(guidBytes);
      console.log(b64encoded);


      Output:



      PcT9u5BIWEW7iVDYAgFKlw==





      share|improve this answer

























      • ASCII or UTF8 will make no difference here, since until codepoint 127 they are identical.

        – Sefe
        Mar 26 at 14:00











      • @marko I can't change the .NET code as it is a legacy code. I only have to replicate that in JS.

        – Himanshu Aggarwal
        Mar 26 at 14:05











      • @HimanshuAggarwal I just updated the answer with the Javascript modifications you need to make.

        – Marko Papic
        Mar 26 at 15:18











      • Awesome, @MarkoPapic. Thanks a lot for your valuable inputs. :)

        – Himanshu Aggarwal
        Mar 27 at 6:52















      1














      Your problem is caused by the following:




      • btoa() is using ASCII encoding


      • guid.ToByteArray(); does not use ASCII encoding

      If you modify your C# code like this:



      String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      //Guid guid = new Guid(str);
      //Console.WriteLine(guid);
      // bbfdc43d-4890-4558-bb89-50d802014a97
      //Byte[] bytes = guid.ToByteArray();
      byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
      //Console.WriteLine(bytes); // System.Byte[]
      String s = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
      Console.WriteLine(s);


      You will get the following output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      Which will be the same string as the one returned from the btoa() function:



      var rawString = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var b64encoded = btoa(rawString);
      console.log(b64encoded);


      Output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      UPDATE - Since you can't modify the C# code



      You should adapt your Javascript code by combining Piotr's answer and this SO answer



      function guidToBytes(guid) 
      var bytes = [];
      guid.split('-').map((number, index) =>
      var bytesInChar = index < 3 ? number.match(/.1,2/g).reverse() : number.match(/.1,2/g);
      bytesInChar.map((byte) => bytes.push(parseInt(byte, 16)); )
      );
      return bytes;


      function arrayBufferToBase64(buffer)
      var binary = '';
      var bytes = new Uint8Array(buffer);
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++)
      binary += String.fromCharCode(bytes[i]);

      return btoa(binary);


      var str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var guidBytes = guidToBytes(str);
      var b64encoded = arrayBufferToBase64(guidBytes);
      console.log(b64encoded);


      Output:



      PcT9u5BIWEW7iVDYAgFKlw==





      share|improve this answer

























      • ASCII or UTF8 will make no difference here, since until codepoint 127 they are identical.

        – Sefe
        Mar 26 at 14:00











      • @marko I can't change the .NET code as it is a legacy code. I only have to replicate that in JS.

        – Himanshu Aggarwal
        Mar 26 at 14:05











      • @HimanshuAggarwal I just updated the answer with the Javascript modifications you need to make.

        – Marko Papic
        Mar 26 at 15:18











      • Awesome, @MarkoPapic. Thanks a lot for your valuable inputs. :)

        – Himanshu Aggarwal
        Mar 27 at 6:52













      1












      1








      1







      Your problem is caused by the following:




      • btoa() is using ASCII encoding


      • guid.ToByteArray(); does not use ASCII encoding

      If you modify your C# code like this:



      String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      //Guid guid = new Guid(str);
      //Console.WriteLine(guid);
      // bbfdc43d-4890-4558-bb89-50d802014a97
      //Byte[] bytes = guid.ToByteArray();
      byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
      //Console.WriteLine(bytes); // System.Byte[]
      String s = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
      Console.WriteLine(s);


      You will get the following output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      Which will be the same string as the one returned from the btoa() function:



      var rawString = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var b64encoded = btoa(rawString);
      console.log(b64encoded);


      Output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      UPDATE - Since you can't modify the C# code



      You should adapt your Javascript code by combining Piotr's answer and this SO answer



      function guidToBytes(guid) 
      var bytes = [];
      guid.split('-').map((number, index) =>
      var bytesInChar = index < 3 ? number.match(/.1,2/g).reverse() : number.match(/.1,2/g);
      bytesInChar.map((byte) => bytes.push(parseInt(byte, 16)); )
      );
      return bytes;


      function arrayBufferToBase64(buffer)
      var binary = '';
      var bytes = new Uint8Array(buffer);
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++)
      binary += String.fromCharCode(bytes[i]);

      return btoa(binary);


      var str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var guidBytes = guidToBytes(str);
      var b64encoded = arrayBufferToBase64(guidBytes);
      console.log(b64encoded);


      Output:



      PcT9u5BIWEW7iVDYAgFKlw==





      share|improve this answer















      Your problem is caused by the following:




      • btoa() is using ASCII encoding


      • guid.ToByteArray(); does not use ASCII encoding

      If you modify your C# code like this:



      String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      //Guid guid = new Guid(str);
      //Console.WriteLine(guid);
      // bbfdc43d-4890-4558-bb89-50d802014a97
      //Byte[] bytes = guid.ToByteArray();
      byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
      //Console.WriteLine(bytes); // System.Byte[]
      String s = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
      Console.WriteLine(s);


      You will get the following output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      Which will be the same string as the one returned from the btoa() function:



      var rawString = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var b64encoded = btoa(rawString);
      console.log(b64encoded);


      Output:



      QkJGREM0M0QtNDg5MC00NTU4LUJCODktNTBEODAyMDE0QTk3


      UPDATE - Since you can't modify the C# code



      You should adapt your Javascript code by combining Piotr's answer and this SO answer



      function guidToBytes(guid) 
      var bytes = [];
      guid.split('-').map((number, index) =>
      var bytesInChar = index < 3 ? number.match(/.1,2/g).reverse() : number.match(/.1,2/g);
      bytesInChar.map((byte) => bytes.push(parseInt(byte, 16)); )
      );
      return bytes;


      function arrayBufferToBase64(buffer)
      var binary = '';
      var bytes = new Uint8Array(buffer);
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++)
      binary += String.fromCharCode(bytes[i]);

      return btoa(binary);


      var str = "BBFDC43D-4890-4558-BB89-50D802014A97";
      var guidBytes = guidToBytes(str);
      var b64encoded = arrayBufferToBase64(guidBytes);
      console.log(b64encoded);


      Output:



      PcT9u5BIWEW7iVDYAgFKlw==






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 26 at 15:17

























      answered Mar 26 at 12:54









      Marko PapicMarko Papic

      7922 silver badges14 bronze badges




      7922 silver badges14 bronze badges












      • ASCII or UTF8 will make no difference here, since until codepoint 127 they are identical.

        – Sefe
        Mar 26 at 14:00











      • @marko I can't change the .NET code as it is a legacy code. I only have to replicate that in JS.

        – Himanshu Aggarwal
        Mar 26 at 14:05











      • @HimanshuAggarwal I just updated the answer with the Javascript modifications you need to make.

        – Marko Papic
        Mar 26 at 15:18











      • Awesome, @MarkoPapic. Thanks a lot for your valuable inputs. :)

        – Himanshu Aggarwal
        Mar 27 at 6:52

















      • ASCII or UTF8 will make no difference here, since until codepoint 127 they are identical.

        – Sefe
        Mar 26 at 14:00











      • @marko I can't change the .NET code as it is a legacy code. I only have to replicate that in JS.

        – Himanshu Aggarwal
        Mar 26 at 14:05











      • @HimanshuAggarwal I just updated the answer with the Javascript modifications you need to make.

        – Marko Papic
        Mar 26 at 15:18











      • Awesome, @MarkoPapic. Thanks a lot for your valuable inputs. :)

        – Himanshu Aggarwal
        Mar 27 at 6:52
















      ASCII or UTF8 will make no difference here, since until codepoint 127 they are identical.

      – Sefe
      Mar 26 at 14:00





      ASCII or UTF8 will make no difference here, since until codepoint 127 they are identical.

      – Sefe
      Mar 26 at 14:00













      @marko I can't change the .NET code as it is a legacy code. I only have to replicate that in JS.

      – Himanshu Aggarwal
      Mar 26 at 14:05





      @marko I can't change the .NET code as it is a legacy code. I only have to replicate that in JS.

      – Himanshu Aggarwal
      Mar 26 at 14:05













      @HimanshuAggarwal I just updated the answer with the Javascript modifications you need to make.

      – Marko Papic
      Mar 26 at 15:18





      @HimanshuAggarwal I just updated the answer with the Javascript modifications you need to make.

      – Marko Papic
      Mar 26 at 15:18













      Awesome, @MarkoPapic. Thanks a lot for your valuable inputs. :)

      – Himanshu Aggarwal
      Mar 27 at 6:52





      Awesome, @MarkoPapic. Thanks a lot for your valuable inputs. :)

      – Himanshu Aggarwal
      Mar 27 at 6:52













      1














      The problem with your code is representation of Guid. In C# code you are converting "BBFDC43D-4890-4558-BB89-50D802014A97" into UUID which is a 128-bit number. In JavaScript code, you are doing something else. You iterate through the string and calculate a byte array of a string. They are simply not equal.
      Now you have to options



      1. Implement proper guid conversion in JS (this may help: https://gist.github.com/daboxu/4f1dd0a254326ac2361f8e78f89e97ae)

      2. In C# calculate byte array in the same way as in JS





      share|improve this answer



























        1














        The problem with your code is representation of Guid. In C# code you are converting "BBFDC43D-4890-4558-BB89-50D802014A97" into UUID which is a 128-bit number. In JavaScript code, you are doing something else. You iterate through the string and calculate a byte array of a string. They are simply not equal.
        Now you have to options



        1. Implement proper guid conversion in JS (this may help: https://gist.github.com/daboxu/4f1dd0a254326ac2361f8e78f89e97ae)

        2. In C# calculate byte array in the same way as in JS





        share|improve this answer

























          1












          1








          1







          The problem with your code is representation of Guid. In C# code you are converting "BBFDC43D-4890-4558-BB89-50D802014A97" into UUID which is a 128-bit number. In JavaScript code, you are doing something else. You iterate through the string and calculate a byte array of a string. They are simply not equal.
          Now you have to options



          1. Implement proper guid conversion in JS (this may help: https://gist.github.com/daboxu/4f1dd0a254326ac2361f8e78f89e97ae)

          2. In C# calculate byte array in the same way as in JS





          share|improve this answer













          The problem with your code is representation of Guid. In C# code you are converting "BBFDC43D-4890-4558-BB89-50D802014A97" into UUID which is a 128-bit number. In JavaScript code, you are doing something else. You iterate through the string and calculate a byte array of a string. They are simply not equal.
          Now you have to options



          1. Implement proper guid conversion in JS (this may help: https://gist.github.com/daboxu/4f1dd0a254326ac2361f8e78f89e97ae)

          2. In C# calculate byte array in the same way as in JS






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 26 at 12:17









          Piotr StappPiotr Stapp

          15.1k5 gold badges51 silver badges92 bronze badges




          15.1k5 gold badges51 silver badges92 bronze badges





















              0














              Your string is a hexadecimal value, which you use to create a GUID. Then you convert the GUID into a byte array with:



              Byte[] bytes = guid.ToByteArray();


              The GUID is a 16-byte value which can be represented as a hexadecimal value. When you convert this GUID into a byte array, you will get the 16 bytes of the value, not the byte representation of the hexadecimal value.



              In the provided JavaScript function you are doing something else: You are converting the string directly to a byte array.



              In C# you do the equivalent with an Encoding:



              String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
              Byte[] bytes = Encoding.UTF8.GetBytes(str);





              share|improve this answer



























                0














                Your string is a hexadecimal value, which you use to create a GUID. Then you convert the GUID into a byte array with:



                Byte[] bytes = guid.ToByteArray();


                The GUID is a 16-byte value which can be represented as a hexadecimal value. When you convert this GUID into a byte array, you will get the 16 bytes of the value, not the byte representation of the hexadecimal value.



                In the provided JavaScript function you are doing something else: You are converting the string directly to a byte array.



                In C# you do the equivalent with an Encoding:



                String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
                Byte[] bytes = Encoding.UTF8.GetBytes(str);





                share|improve this answer

























                  0












                  0








                  0







                  Your string is a hexadecimal value, which you use to create a GUID. Then you convert the GUID into a byte array with:



                  Byte[] bytes = guid.ToByteArray();


                  The GUID is a 16-byte value which can be represented as a hexadecimal value. When you convert this GUID into a byte array, you will get the 16 bytes of the value, not the byte representation of the hexadecimal value.



                  In the provided JavaScript function you are doing something else: You are converting the string directly to a byte array.



                  In C# you do the equivalent with an Encoding:



                  String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
                  Byte[] bytes = Encoding.UTF8.GetBytes(str);





                  share|improve this answer













                  Your string is a hexadecimal value, which you use to create a GUID. Then you convert the GUID into a byte array with:



                  Byte[] bytes = guid.ToByteArray();


                  The GUID is a 16-byte value which can be represented as a hexadecimal value. When you convert this GUID into a byte array, you will get the 16 bytes of the value, not the byte representation of the hexadecimal value.



                  In the provided JavaScript function you are doing something else: You are converting the string directly to a byte array.



                  In C# you do the equivalent with an Encoding:



                  String str = "BBFDC43D-4890-4558-BB89-50D802014A97";
                  Byte[] bytes = Encoding.UTF8.GetBytes(str);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 26 at 12:19









                  SefeSefe

                  11.4k5 gold badges29 silver badges46 bronze badges




                  11.4k5 gold badges29 silver badges46 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55356285%2fhow-to-convert-a-string-to-base64-encoding-using-byte-array-in-javascript%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript