function utf8BytesToString(bytes) { if (!bytes || bytes.length === 0) return ''; // 如果传入的不是 Uint8Array,尝试转为 Uint8Array if (!(bytes instanceof Uint8Array)) { bytes = new Uint8Array(bytes); } let result = ''; let i = 0; while (i < bytes.length) { const byte1 = bytes[i]; if ((byte1 & 0x80) === 0) { // 1字节字符:0xxxxxxx (ASCII) result += String.fromCharCode(byte1); i += 1; } else if ((byte1 & 0xE0) === 0xC0) { // 2字节字符:110xxxxx 10xxxxxx if (i + 1 >= bytes.length) break; // 不足,跳过 const byte2 = bytes[i + 1]; if ((byte2 & 0xC0) !== 0x80) { i += 1; continue; // 非法 UTF-8,跳过 } const codePoint = ((byte1 & 0x1F) << 6) | (byte2 & 0x3F); result += String.fromCharCode(codePoint); i += 2; } else if ((byte1 & 0xF0) === 0xE0) { // 3字节字符:1110xxxx 10xxxxxx 10xxxxxx if (i + 2 >= bytes.length) break; const byte2 = bytes[i + 1]; const byte3 = bytes[i + 2]; if ((byte2 & 0xC0) !== 0x80 || (byte3 & 0xC0) !== 0x80) { i += 1; continue; // 非法,跳过 } const codePoint = ((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F); result += String.fromCharCode(codePoint); i += 3; } else if ((byte1 & 0xF8) === 0xF0) { // 4字节字符:11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // (可选支持,一般小程序/中文足够用 3 字节) if (i + 3 >= bytes.length) break; // 你可以选择继续实现 4 字节,但大多数情况下 3 字节足够覆盖中文 i += 1; continue; } else { // 非法 UTF-8 起始字节,跳过 i += 1; } } return result; } let text = utf8BytesToString(res.data);
小程序不支持TextDecoder?下载云存储的json文件,涉及汉字转码问题,开发工具上完整运行 let gbk = new TextDecoder('gbk').decode(new Uint8Array(res.data)) //这里把gbk文件读入转换成了utf8的String 真机上 TypeError: TextDecoder is not a constructor 求高手解答
09-19