Last active: a year ago
unicodeAndAscii
/**
* 将 Unicode 编码为 ASCII
*/
export const toBinary = (target: string): string => {
const codeUnits = new Uint16Array(target.length);
for (let i = 0; i < codeUnits.length; i++) {
codeUnits[i] = target.charCodeAt(i);
}
const charCodes = new Uint8Array(codeUnits.buffer);
let result = '';
for (let i = 0; i < charCodes.byteLength; i++) {
result += String.fromCharCode(charCodes[i]);
}
return result;
};
/**
* 将 toBinary 编码过的 ASCII 解码为 Unicode
*/
export const fromBinary = (target: string): string => {
const bytes = new Uint8Array(target.length);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = target.charCodeAt(i);
}
const charCodes = new Uint16Array(bytes.buffer);
let result = '';
for (let i = 0; i < charCodes.length; i++) {
result += String.fromCharCode(charCodes[i]);
}
return result;
};