Languages
[Edit]
EN

JavaScript - convert string to bytes array under Node.js

9 points
Created by:
Richard-Bevan
253

In this short article, we would like to show, how using JavaScript, 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.

Practical example:

1. to UTF-8 bytes:

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


// Usage example:

const bytes = toBytes('Some text here...');

console.log(bytes);

Note: go to this article to see pure JavaScript solution.

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 = (string) => {
	const buffer = Buffer.from(string, 'utf16le');
	const result = Array(buffer.length);
	for (var i = 0; i < buffer.length; i++) {
		result[i] = buffer[i];
	}
	return result;
};


// Usage example:

const bytes = 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

  3. JavaScript - convert string to bytes array - Universal Approach

  4. JavaScript - convert bytes array to string - Universal Approach

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