Languages
[Edit]
EN

TypeScript - convert string to bytes array under Node.js

0 points
Created by:
Vanessa-Drake
718

In this short article, we would like to show, how using TypeScript, convert string to bytes array under Node.js.

Hint: converting string to bytes you need to select the encoding type that should be used to produce bytes array.

1. to UTF-8 bytes:

const toBytes = (text: string): number[] => {
    const buffer = Buffer.from(text, 'utf8');
    const result = Array(buffer.length);
    for (let i = 0; i < buffer.length; ++i) {
        result[i] = buffer[i];
    }
    return result;
};


// Usage example:

const bytes: number[] = toBytes('Some text here...');

console.log(bytes);

Output:

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

2. to UTF-16 LE bytes:

const toBytes = (text: string): number[] => {
    const buffer = Buffer.from(text, 'utf16le');
    const result = Array(buffer.length);
    for (let i = 0; i < buffer.length; ++i) {
        result[i] = buffer[i];
    }
    return result;
};


// Usage example:

const bytes: number[] = toBytes('Some text here...');

console.log(bytes);

Output:

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

See also

  1. ASCII Table

  2. ASCII Table in plain/text

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