Skip to content

Instantly share code, notes, and snippets.

@eczn
Last active April 27, 2022 08:33
Show Gist options
  • Save eczn/55ce04d8ee01c2343ace78e25b085d82 to your computer and use it in GitHub Desktop.
Save eczn/55ce04d8ee01c2343ace78e25b085d82 to your computer and use it in GitHub Desktop.
解决 utf-8 base64 编码乱码

乱码不是乱码 而是二进制 base64

https://git.coolaj86.com/coolaj86/unibabel.js/src/branch/master/index.js

base64 解中文会乱码,原因是解出来的东西是一个 8 位整数,你得对这个整数进行 .toString(8) 并在前面加上 % 变成形如 %E5%B1%8E 这样的字符串,再进行 decodeComponentURI

那么反过来呢?

汉字转 binary bytes (base64-expression)

btoa(encodeURIComponent('爷青结').split('%').filter(e => !!e).map(e => String.fromCharCode(parseInt(e, 16))).join(''));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment