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.
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);
};