Search code examples
javascriptstringradix

JS base n string to base64


I have a string (with numbers under 128) separated by a comma:

"127,25,34,52,46,2,34,4,6,1"

Because there are 10 digits and one comma, that makes 11 total characters. How can I convert this string from "base 11" to "base 64"? I would like to compress this string into base64. I tried window.btoa, but it produces a larger output because the browser doesn't know that the string only has 11 characters.

Thanks in advance.


Solution

  • Base64 encoding never produces shorter strings. It is not intended as a compression tool, but as a means to reduce the used character set to 64 readable characters, taking into account that the input may use a larger characterset (even if not all those characters are used).

    Given the format of your string, why not take those numbers and use them as ASCII, and then apply Base64 encoding on that?

    Demo:

    let s = "127,25,34,52,46,2,34,4,6,1";
    console.log(s);
    
    let encoded = btoa(String.fromCharCode(...s.match(/\d+/g)));
    console.log(encoded);
    
    let decoded = Array.from(atob(encoded), c => c.charCodeAt()).join();
    console.log(decoded);