EN
TypeScript - convert bytes array to string
0 points
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.
xxxxxxxxxx
1
const toText = (bytes: number[]): string => {
2
let result = '';
3
for (let i = 0; i < bytes.length; ++i) {
4
const byte = bytes[i];
5
const text = byte.toString(16);
6
result += (byte < 16 ? '%0' : '%') + text;
7
}
8
return decodeURIComponent(result);
9
};
10
11
12
// Usage example:
13
14
const bytes: number[] = [83, 111, 109, 101, 32, 116, 101, 120, 116, 32, 104, 101, 114, 101, 46, 46, 46];
15
const text: string = toText(bytes);
16
17
console.log(text);
Output:
xxxxxxxxxx
1
Some text here...
xxxxxxxxxx
1
const toText = (bytes: number[]): string => {
2
let result = '';
3
for (let i = 0; i < bytes.length; ++i) {
4
const byte = bytes[i];
5
const text = byte.toString(16);
6
result += (byte < 16 ? '%0' : '%') + text;
7
}
8
return decodeURIComponent(result);
9
};