In JavaScript you can convert a number to a string representation with a specific radix 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. I'm not.
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).
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.