Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write javascript equivalent of Convert.ToBase64String() in javascript? [duplicate]

Tags:

javascript

c#

I have byte array and I can convert this usin Convert.ToBase64String() method in c#. I wrote equivalent of this method in javascript like below. But the result is different.

in c#:

 byte[] data = ...
Convert.ToBase64String(data)

in js

    function GetStringFromByteArray(array) {
        var result = "";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++)
                result += String.fromCharCode(array[i][j]);
        }
        return result;
    }

How can I succeed this in js?

like image 308
Mehmet Ince Avatar asked May 15 '13 10:05

Mehmet Ince


2 Answers

Yes, the result is different, because the Javascript function doesn't do base64 encoding at all.

The base64 encoded data contains six bits of information per character, so the eight bits of a character code is spread out over two characters in the encoded data.

To encode the data, you have to regroup the bits in the bytes into six bit groups, then you can convert each group into a base64 character.

See: Base64

like image 98
Guffa Avatar answered Sep 24 '22 05:09

Guffa


You can use this javascript library

like image 24
72DFBF5B A0DF5BE9 Avatar answered Sep 22 '22 05:09

72DFBF5B A0DF5BE9