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));
      }

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

Comments

0

This will allow unicode characters

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

1 Comment

Thank you @Zinc , but Uint16Array shows output something like 䘣䅌䝇⁁ਰ倣佒則䵁∠楄楧慴慬蘠獲
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.

3 Comments

function ab2str(buf) { return String.fromCharCode.apply(null, new Uint16Array(buf)); } - Same code I am using, It is not working
Can you post a codepen, a jsbin or similar with an example of your issue so we can help?
I just found - String.fromCharCode.apply(null, [134]) - this isnt working.
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;
  }

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.