2

I am stuck in converting arraybuffer to string in typescript (angular 4 project). Any help is highly appreciated.

Code output is showing string but with this sign - �

Required Output :

PROGRAM "Digitala †rsredovisningen"

Getting Output :

PROGRAM "Digitala �rsredovisningen"

  
ab2str(arraybuffer) {
        return String.fromCharCode.apply(null, new Uint8Array(arraybuffer));
      }
Community
  • 1
  • 1
Shifali singla
  • 76
  • 1
  • 2
  • 8

5 Answers5

2

You should try something like this:

function uintToString(uintArray) {
    var encodedString = String.fromCharCode.apply(null, uintArray),
        decodedString = decodeURIComponent(escape(encodedString));
    return decodedString;
}

Maybe this will help:

https://ourcodeworld.com/articles/read/164/how-to-convert-an-uint8array-to-string-in-javascript

Calin Vlasin
  • 1,331
  • 1
  • 15
  • 21
0

This will allow unicode characters

ab2str(arraybuffer) {
    return String.fromCharCode.apply(null, new Uint16Array(arraybuffer));
  }
curv
  • 3,796
  • 4
  • 33
  • 48
0

From this reference you can check the following:

function ab2str(buf) {
  return String.fromCharCode.apply(null, new Uint16Array(buf));
}

function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

Additionally, if you can use using TextEncoder and TextEncoder, check this answer.

David Pelayo
  • 158
  • 10
0

This worked for me.

I had a SHA256 hash that i needed to convert to String.

function ab2str(hashBuffer) {
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
  }
abhi5800
  • 374
  • 1
  • 5
  • 21
0

If you are having the same problem as Shifali singla (chinese characters) just change this:

return String.fromCharCode.apply(null, new Uint16Array(arraybuffer));

to this

return String.fromCharCode.apply(null, new Uint8Array(arraybuffer));

the buffer is probably coming in a unit8array and not in a unit16array