Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active March 20, 2021 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpivo/7d1d765a1b3ab4f3155d4a553bc52ab1 to your computer and use it in GitHub Desktop.
Save rpivo/7d1d765a1b3ab4f3155d4a553bc52ab1 to your computer and use it in GitHub Desktop.
Using string.FromCharCode() to Read Byte Arrays In JavaScript

Using string.FromCharCode() to Read Byte Arrays In JavaScript

string.FromCharCode() can be useful to convert a byte array into a readable string.

console.log(String.fromCharCode(65, 66, 67));
// ABC

Here's what this would look like when encoding a string with TextEncoder, and then converting this string back to readable text using fromCharCode:

const encoded = new TextEncoder().encode('food') // creates a Uint8Array containing [102, 111, 111, 100]

console.log(
  // we first need to convert the Uint8Array to a regular array using Array.from()
  // then, we destructure this array into fromCharCode()
  String.fromCharCode(...Array.from(encoded))
)
// food
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment