📅  最后修改于: 2022-03-11 15:03:18.802000             🧑  作者: Mango
function toBinary(string) {
const codeUnits = new Uint16Array(string.length);
for (let i = 0; i < codeUnits.length; i++) {
codeUnits[i] = string.charCodeAt(i);
}
return String.fromCharCode(...new Uint8Array(codeUnits.buffer));
}
function fromBinary(binary) {
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return String.fromCharCode(...new Uint16Array(bytes.buffer));
}
const myString = "â¸â¹âºâ»â¼â¾â¿"
// console.log(btoa(myString)) // Error InvalidCharacterError: The string to be encoded contains characters outside of the Latin1 range.
const converted = toBinary(myString)
const encoded = btoa(converted)
console.log(encoded)
const decoded = atob(encoded)
const original = fromBinary(decoded)
console.log(original);