Inspirado en la respuesta de @ hgoebl. Su código es para UTF-16 y necesitaba algo para US-ASCII. Entonces, aquí hay una respuesta más completa que cubre US-ASCII, UTF-16 y UTF-32.
function stringToAsciiByteArray(str)
{
var bytes = [];
for (var i = 0; i < str.length; ++i)
{
var charCode = str.charCodeAt(i);
if (charCode > 0xFF)
{
throw new Error('Character ' + String.fromCharCode(charCode) + ' can\'t be represented by a US-ASCII byte.');
}
bytes.push(charCode);
}
return bytes;
}
function stringToUtf16ByteArray(str)
{
var bytes = [];
for (var i = 0; i < str.length; ++i)
{
var charCode = str.charCodeAt(i);
bytes.push((charCode & 0xFF00) >>> 8);
bytes.push(charCode & 0xFF);
}
return bytes;
}
function stringToUtf32ByteArray(str)
{
var bytes = [];
for (var i = 0; i < str.length; i+=2)
{
var charPoint = str.codePointAt(i);
bytes.push((charPoint & 0xFF000000) >>> 24);
bytes.push((charPoint & 0xFF0000) >>> 16);
bytes.push((charPoint & 0xFF00) >>> 8);
bytes.push(charPoint & 0xFF);
}
return bytes;
}
UTF-8 es de longitud variable y no está incluido porque tendría que escribir la codificación yo mismo. UTF-8 y UTF-16 son de longitud variable. UTF-8, UTF-16 y UTF-32 tienen un número mínimo de bits como lo indica su nombre. Si un carácter UTF-32 tiene un punto de código de 65, significa que hay 3 ceros a la izquierda. Pero el mismo código para UTF-16 solo tiene 1 0 a la izquierda. Por otro lado, US-ASCII tiene un ancho fijo de 8 bits, lo que significa que se puede traducir directamente a bytes.
String.prototype.charCodeAtdevuelve un número máximo de 2 bytes y coincide exactamente con UTF-16. Sin embargo, String.prototype.codePointAtse necesita UTF-32, que es parte de la propuesta ECMAScript 6 (Harmony). Debido a que charCodeAt devuelve 2 bytes, que son más caracteres posibles de los que puede representar US-ASCII, la función stringToAsciiByteArrayarrojará en tales casos en lugar de dividir el carácter por la mitad y tomar uno o ambos bytes.
Tenga en cuenta que esta respuesta no es trivial porque la codificación de caracteres no es trivial. El tipo de matriz de bytes que desee dependerá de la codificación de caracteres que desee que representen esos bytes.
javascript tiene la opción de usar internamente UTF-16 o UCS-2, pero como tiene métodos que actúan como si fuera UTF-16, no veo por qué cualquier navegador usaría UCS-2. Ver también: https://mathiasbynens.be/notes/javascript-encoding
Sí, sé que la pregunta tiene 4 años, pero necesitaba esta respuesta para mí.