Languages
[Edit]
EN

TypeScript - convert string to bytes array

0 points
Created by:
cory
1786

In this short article, we would like to show, how using TypeScriptconvert string to bytes array.

Hint: below solution works under web browser and Node.js TypeScript.

Practical example

const toBytes = (text: string): number[] => {
  const surrogate = encodeURIComponent(text);
  const result = [];
  for (let i = 0; i < surrogate.length; ) {
    const character = surrogate[i];
    i += 1;
    if (character == '%') {
      const hex = surrogate.substring(i, (i += 2));
      if (hex) {
        result.push(parseInt(hex, 16));
      }
    } else {
      result.push(character.charCodeAt(0));
    }
  }
  return result;
};


// Usage example:

const bytes: number[] = toBytes('Some text here...'); // converts string to UTF-8 bytes

console.log(bytes);

Output:

[83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46]

See also

  1. JavaScript - convert string to bytes array

Alternative titles

  1. TypeScript - convert string to utf8 bytes array
  2. TypeScript - convert string to UTF-8 bytes array
  3. TypeScript - bytes array from string
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join