0

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)

Jaco
  • 11
  • 1
  • 4

2 Answers2

3

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.

zswang
  • 2,302
  • 3
  • 16
  • 13
2

use TextDecoder. like this one:

const decoder = new TextDecoder("utf-8");
const str = decoder.decode(Buffer.from([0xAA, 0xAA]));
Reza Bayat
  • 393
  • 2
  • 5