微信小游戏平台有什么utf8 str 转uint8 Array的方法吗

我们的加解密 需要 utf8 和uint8 array 互转
网上找的方法 都是需要dom环境的
btoa encodeURIComponent 都不支持
大家有什么好方法吗

自己实现了一个
strToUint = function(_string:string) {
if(!_string)
return [];
let string = encodeURIComponent(_string);
let uintArray = [];
let i = 0;
while(i<string.length){
if(string[i] == ‘%’){
// let b = + string[i+2];
// cc.log(‘b=’+b);
uintArray.push(parseInt(string[++i] + string[++i], 16));
i++;
} else{
uintArray.push(string.charCodeAt(i++));
}
}
return new Uint8Array(uintArray);
};
//网上找的
uintToStr = function(strBytes:Uint8Array):string{
var MAX_SIZE = 0x4000;
var codeUnits = [];
var highSurrogate;
var lowSurrogate;
var index = -1;

var result = '';
while (++index < strBytes.length) {
    var codePoint = Number(strBytes[index]);

    if (codePoint === (codePoint & 0x7F)) {

    } else if (0xF0 === (codePoint & 0xF0)) {
        codePoint ^= 0xF0;
        codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
        codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
        codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
    } else if (0xE0 === (codePoint & 0xE0)) {
        codePoint ^= 0xE0;
        codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
        codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
    } else if (0xC0 === (codePoint & 0xC0)) {
        codePoint ^= 0xC0;
        codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80);
    }

    if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || Math.floor(codePoint) != codePoint)
        throw RangeError('Invalid code point: ' + codePoint);

    if (codePoint <= 0xFFFF)
        codeUnits.push(codePoint);
    else {
        codePoint -= 0x10000;
        highSurrogate = (codePoint >> 10) | 0xD800;
        lowSurrogate = (codePoint % 0x400) | 0xDC00;
        codeUnits.push(highSurrogate, lowSurrogate);
    }
    if (index + 1 == strBytes.length || codeUnits.length > MAX_SIZE) {
        result += String.fromCharCode.apply(null, codeUnits);
        codeUnits.length = 0;
    }
}

return result;

};

遇到过同样的问题,目前也只是上面的纯JS硬算。如果ByteArray比较短还好,长了就会有效率问题。String.fromCharCode.apply(null, codeUnits); 这行代码对codeUnits有长度限制,大概超过16K左右就会异常。

1赞

好的 多谢提醒