How can I encode arbitrary bytes / data in base64 format using Javascript?

For example, let's say I wanted to encode a 64-bit signed integer in base64, how could I (if possible) do this in Javascript?

To clarify, I want to encode the actual bits / bytes of the data, not a string or string representation of the data.

those. the integer 15 in decimal is 0000 1111 in binary, which is Dw == in base64.

I don’t want to encode the string representation of the integer 15. For comparison, if you encode the string β€œ15” in base64, you actually encode 0011 0001 0011 0101, which will give you MTU = in base64 form (this is what window.atob() does window.atob() ).

+4
source share
2 answers

Convert to a string first, then use btoa or one of the other standard b64 encoders:

 window.btoa(String.fromCharCode(15)); // Dw== 
+3
source

You can use window.btoa () in browsers that support it, in other browsers you can use this encoder .

- change

You will have to write everything yourself, since everything that you pass to window.btoa is first converted to a string. This answer may be a good place to start; although Gears has been discontinued, many of the related functions are in the HTML5 / W3C File API , which has some experimental implementations .

+2
source

All Articles