【问题标题】:JS base n string to base64JS base n字符串到base64
【发布时间】:2021-01-01 22:08:13
【问题描述】:

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

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

因为有 10 个数字和一个逗号,所以总共有 11 个字符。如何将此字符串从“base 11”转换为“base 64”?我想将此字符串压缩为base64。我试过window.btoa,但它会产生更大的输出,因为浏览器不知道该字符串只有11个字符。

提前致谢。

【问题讨论】:

  • 10 digits and one comma 但我计算了 10 个数字,由 17 个数字和 9 个逗号组成,总共 26 个字符。 "How can I convert this string from "base 11" 这个字符串不在 base11 中。 I would like to compress this string into base64 base64 总是创建一个更大的字符串,它不会压缩它。 but it produces a larger output because the browser doesn't know that the string only has 11 characters 它不仅有 11 个字符,还有 26 个字符,不管怎样,base64 总是会创建一个更大的字符串
  • base64 有严格的定义,不是压缩工具。你想要压缩......这不叫base64。
  • 字符集有 11 个字符,就像 base64 有 64 个字符一样。我知道对于 ASCII,base64 不是“压缩”,因为 128>64。但是对于 11 个字符来说,就是“压缩”了。
  • 将十六进制转换为base64会使其更短吗?是的,因为 16
  • 我认为 127 - 是七位,你可以从八个数字中累积 1 个字节

标签: javascript string base


【解决方案1】:

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多