Skip to content Skip to sidebar Skip to footer

How Do I Convert A String In Javascript To A Sequence Of Bytes?

In Python 3, to convert a string to sequence of bytes, one uses String.encode(ENCODING) where ENCODING is the name of the encoding to use. If I have a character in my string that h

Solution 1:

You can use TextEncoder().encode() and TextDecoder().decode() methods

let decoder = new TextDecoder(/* character encoding */);
let encoder = new TextEncoder();

let encoded = encoder.encode(str);
let decoded = decoder.decode(encoded);

Solution 2:

You can read the bytes directly with the standard FileReader:

var str = "Āabc";
var b = newBlob([str], {type:"text/plain"});
var f = newFileReader();
f.addEventListener("loadend", function(){
    console.log(newUint8Array(f.result));    // [196, 128, 97, 98, 99]
});
f.readAsArrayBuffer(b);

Solution 3:

"operate on the string for … a cipher": Probably not.

Ciphers are mathematical transformations of byte arrays. The result of encryption is not text so it can't be directly stored in a string.

A JavaScript string is a counted sequence of UTF-16 code units. (Also applies to VB4/5/6, VB, VBA, VBScript, C#, Java….) UTF-16 is one of several encoding of the Unicode character set. UTF-8 is another. Neither encodes to/decodes from arbitrary binary data.

You mentioned String.charCodeAt(). This just gives you one of the UTF-16 code units from the string.

Common ways of carrying and displaying binary data in strings are Base64 and hexadecimal. It's a bit weightier that way—and sender and receiver have to agree on both the character encoding of the string and the binary-to-text transformation—but many systems would rather pass text than binary.

Post a Comment for "How Do I Convert A String In Javascript To A Sequence Of Bytes?"