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