admin管理员组文章数量:1332873
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
本文标签: javascriptConverting array buffer in stringStack Overflow
版权声明:本文标题:javascript - Converting array buffer in string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742320575a2452702.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论