Array di byte UTF-16
JavaScript codifica le stringhe come UTF-16 , proprio come C # UnicodeEncoding, quindi gli array di byte devono corrispondere esattamente utilizzando charCodeAt()e suddividendo ciascuna coppia di byte restituita in 2 byte separati, come in:
function strToUtf16Bytes(str) {
const bytes = [];
for (ii = 0; ii < str.length; ii++) {
const code = str.charCodeAt(ii);
bytes.push(code & 255, code >> 8);
}
return bytes;
}
Per esempio:
strToUtf16Bytes('🌵');
Tuttavia, se si desidera ottenere un array di byte UTF-8, è necessario transcodificare i byte.
UTF-8 Byte Array
La soluzione sembra in qualche modo non banale, ma ho utilizzato il codice seguente in un ambiente di produzione ad alto traffico con grande successo ( fonte originale ).
Inoltre, per il lettore interessato, ho pubblicato i miei helper Unicode che mi aiutano a lavorare con le lunghezze di stringa riportate da altri linguaggi come PHP.
export function strToUtf8Bytes(str) {
const utf8 = [];
for (let ii = 0; ii < str.length; ii++) {
let charCode = str.charCodeAt(ii);
if (charCode < 0x80) utf8.push(charCode);
else if (charCode < 0x800) {
utf8.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
} else if (charCode < 0xd800 || charCode >= 0xe000) {
utf8.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
} else {
ii++;
charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff));
utf8.push(
0xf0 | (charCode >> 18),
0x80 | ((charCode >> 12) & 0x3f),
0x80 | ((charCode >> 6) & 0x3f),
0x80 | (charCode & 0x3f),
);
}
}
return utf8;
}