Menu
In JavaScript you can convert a number to a string representation with a specific as follows: (12345).toString(36) // '9ix'.and you can convert it back to a regular number like this: parseInt('9ix', 36) // 12345 36 is the highest radix you can specify. It apparently uses the characters 0-9 and a-z for the digits (36 total).
My question: what's the fastest way to convert a number to a base 64 representation (for example, using A-Z, and - and for the extra 28 digits)? Update: Four people have posted responses saying this question is duplicated, or that I'm looking for Base64. ' is a way of encoding binary data in a simple ASCII character set, to make it safe for transfer over networks etc. (so that text-only systems won't garble the binary).
Dawns on me you can convert to base 8, and then the transformation from base 8 to base 64 is trivial, each pair of base 8 digits results in a single base64 digit. Conveniently Decode Base 64 Data and Encode text and files to Base 64 data. This is a convienent online tool that allows you to convert to and from base64 data. You can encode and decode text, images, spreadsheets, documents - you name it.
That's not what I'm asking about. I'm asking about converting numbers to a radix 64 string representation. (JavaScript's toString(radix) does this automatically for any radix up to 36; I need a custom function to get radix 64.) Update 2: Here are some input & output examples. 0 → '0' 1 → '1' 9 → '9' 10 → 'a' 35 → 'z' 61 → 'Z' 62 → '-' 63 → ' 64 → '10' 65 → '11' 128 → '20' etc.
I wrote an npm module for this type of operation, that will help you. You can convert any number from any radix to any radix in a user-defined character encoding. For example: var base = 'Q', 'W', 'E', 'R', 'T', 'Y', 'I', 'O', 'U'; new PowerRadix(1, 0, 10).toArray(base); // 'W', 'Q' new PowerRadix('10', 10).toArray(base); // 'W', 'Q' new PowerRadix(10, 10).toArray(base); // 'W', 'Q' new PowerRadix(1, 0, 10).toString(base); // 'WQ' new PowerRadix('10', 10).toString(base); // 'WQ' new PowerRadix(10, 10).toString(base); // 'WQ' The module also supports custom source radix encodings. New PowerRadix('ba', 'a', 'b'); // base 2 source radix, uses 'a' = 0 & 'b' = 1 character set. New PowerRadix('ba', 'a', 'b').toString(10); // returns '2'.