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)

2
  • If your browser supports it => stackoverflow.com/a/41180394/7131047 Commented May 12, 2017 at 9:38
  • Are you using Node.js or is the Javascript running in the browser? Commented May 12, 2017 at 10:38

2 Answers 2

3

use TextDecoder. like this one:

const decoder = new TextDecoder("utf-8");
const str = decoder.decode(Buffer.from([0xAA, 0xAA]));
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.