Languages
[Edit]
EN

TypeScript - convert bytes array to string

0 points
Created by:
Mariam-Barron
841

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

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

1. from UTF-8 bytes:

const toText = (bytes: number[]): string => {
    let result = '';
    for (let i = 0; i < bytes.length; ++i) {
        const byte = bytes[i];
        const text = byte.toString(16);
        result += (byte < 16 ? '%0' : '%') + text;
    }
    return decodeURIComponent(result);
};


// Usage example:

const bytes: number[] = [83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46];
const text: string = toText(bytes);

console.log(text);

Output:

Some text here...

Short version

const toText = (bytes: number[]): string => {
    let result = '';
    for (let i = 0; i < bytes.length; ++i) {
        const byte = bytes[i];
        const text = byte.toString(16);
        result += (byte < 16 ? '%0' : '%') + text;
    }
    return decodeURIComponent(result);
};

See also

  1. TypeScript - convert string to bytes array

  2. TypeScript - convert string to bytes array under Node.js

Alternative titles

  1. TypeScript - string from bytes array
  2. TypeScript - convert utf8 bytes array to string
  3. TypeScript - convert UTF-8 bytes array to 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