6

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

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

I.e. the integer 15 in decimal is equal to 0000 1111 in binary, which is equal to Dw== in base64 form.

I do not want to encode the string representation of the integer 15. For comparison, if you encode the string "15" in base64, you are actually encoding 0011 0001 0011 0101, which will give you MTU= in base64 form (this is what window.atob() does).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Oaa
  • 63
  • 1
  • 4
  • Why do you need to do this? I.e. Who will be consuming the base64 encoded version of your data? What is the fundamental requirement that you need the binary representation of an integer? – ewh Apr 22 '11 at 19:31
  • You asked for "64 bit" data. As such, your 15 would actually be `00000000 00000000 00000000 00000000 00000000 00000000 00000000 00001111` and would encode as `"AAAAAAAAAA8="` instead of `"DW=="` for your 8-bit example. –  Apr 22 '11 at 19:44

2 Answers2

3

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

window.btoa(String.fromCharCode(15)); // Dw==
user123444555621
  • 148,182
  • 27
  • 114
  • 126
2

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

--edit

You're going to have to write it all yourself, as anything you pass into 'window.btoa' is going to get converted to a string first. This answer may be a good place to start; although Gears has been discontinued a lot of the relevant functionality is in the HTML5/W3C File API, which has some experimental implementations.

Community
  • 1
  • 1
robertc
  • 74,533
  • 18
  • 193
  • 177