Languages
[Edit]
EN

JavaScript - convert bytes array to string

10 points
Created by:
Blessing-D
334

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

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

Practical example:

1. from UTF-8 bytes:

// ONLINE-RUNNER:browser;

const getCode = (byte) => {
  	const text = byte.toString(16);
  	if (byte < 16) {
    	return '%0' + text;
    }
	return '%' + text;
};

const toString = (bytes) => {
  	var result = '';
    for (var i = 0; i < bytes.length; ++i) {
        result += getCode(bytes[i]);
    }
    return decodeURIComponent(result);
};


// Usage example:

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

console.log(string);

See also

  1. JavaScript - convert string to bytes array

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

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