I have a problem. I need communication javascript to C node.
The protocol use a String with 0xAAAA header.
in JS i have a Uint8Array with {\\xAA,\\xAA} My problem is that i need convert a Uint8Array in String UTF-8 .
How to convert from Uint8Array in UTF-8 to uTF-8 string)
have a try:
function str2arr(str) { var utf8 = unescape(encodeURIComponent(str)); return new Uint8Array(utf8.split('').map(function (item) { return item.charCodeAt(); })); } function arr2str(arr) { // or [].slice.apply(arr) var utf8 = Array.from(arr).map(function (item) { return String.fromCharCode(item); }).join(''); return decodeURIComponent(escape(utf8)); } var arr = str2arr('汉字'); document.querySelector('div').innerHTML = arr; document.querySelector('div:nth-of-type(2)').innerHTML = arr2str(arr);
<div></div> <div></div>
[0xAA, 0xAA] is an invalid utf8 array.
For reference: https://github.com/zswang/jpacks Binary data packing and unpacking.
use TextDecoder. like this one:
const decoder = new TextDecoder("utf-8");
const str = decoder.decode(Buffer.from([0xAA, 0xAA]));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.