在微信小程序使用tcp连接过程中,服务器向客户端返回值为ArrayBuffer格式。
如何转换,格式如下:
var buffer = res.message
var a = new Uint8Array(buffer)
var str = ''
for (var i = 0; i <= buffer.byteLength; i++) {
str += String.fromCharCode(a[i])
}
var utftext = str
var string = '';
var i = 0;
let c = 0;
let c1 = 0;
let c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if ((c > 191) && (c < 224)) {
c1 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
} else {
c1 = utftext.charCodeAt(i + 1);
c2 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
console.log(string)