JS base n 字符串转base64
JS base n string to base64
我有一个用逗号分隔的字符串(数字小于 128):
"127,25,34,52,46,2,34,4,6,1"
因为有 10 个数字和一个逗号,所以总共有 11 个字符。如何将此字符串从“base 11”转换为“base 64”?我想将这个字符串压缩成 base64。我尝试了 window.btoa,但它产生了更大的输出,因为浏览器不知道该字符串只有 11 个字符。
提前致谢。
Base64 编码永远不会产生更短的字符串。它不是作为压缩工具,而是作为将使用的字符集减少到 64 个可读字符的一种手段,考虑到输入可能使用更大的字符集(即使不是所有这些字符都被使用)。
鉴于您的字符串格式,为什么不将这些数字用作 ASCII,然后对其应用 Base64 编码?
演示:
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);
我有一个用逗号分隔的字符串(数字小于 128):
"127,25,34,52,46,2,34,4,6,1"
因为有 10 个数字和一个逗号,所以总共有 11 个字符。如何将此字符串从“base 11”转换为“base 64”?我想将这个字符串压缩成 base64。我尝试了 window.btoa,但它产生了更大的输出,因为浏览器不知道该字符串只有 11 个字符。
提前致谢。
Base64 编码永远不会产生更短的字符串。它不是作为压缩工具,而是作为将使用的字符集减少到 64 个可读字符的一种手段,考虑到输入可能使用更大的字符集(即使不是所有这些字符都被使用)。
鉴于您的字符串格式,为什么不将这些数字用作 ASCII,然后对其应用 Base64 编码?
演示:
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);