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));
}
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));
}
Share
Improve this question
edited Jun 20, 2020 at 9:12
CommunityBot
11 silver badge
asked Nov 22, 2017 at 9:57
Shifali singlaShifali singla
761 gold badge2 silver badges8 bronze badges
5 Answers
Reset to default 2You 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./articles/read/164/how-to-convert-an-uint8array-to-string-in-javascript
This will allow unicode characters
ab2str(arraybuffer) {
return String.fromCharCode.apply(null, new Uint16Array(arraybuffer));
}
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.
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;
}
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 ing in a unit8array and not in a unit16array
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742320576a4421726.html
评论列表(0条)