JS base n 字符串转base64

问题描述

我有一个用逗号分隔的字符串(数字小于 128):

"127,25,34,52,46,2,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,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);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...