You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * little arrays (>=100k characters), otherwise you'll get exceptions as RangeError : Maximum call * stack size exceeded or Out of stack space. * @returns {string} */functionuint8arrayToStringMethod(myUint8Arr){returnString.fromCharCode.apply(null,myUint8Arr);}
/** * Convert an Uint8Array into a string. * * @returns {String} */functionDecodeuint8arr(uint8array){returnnewTextDecoder("utf-8").decode(uint8array);}/** * Convert a string into a Uint8Array. * * @returns {Uint8Array} */functionEncodeuint8arr(myString){returnnewTextEncoder("utf-8").encode(myString);}
Crossplatform method
跨平台依赖性低运行良好
// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt/* utf.js - UTF-8 <=> UTF-16 convertion * * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp> * Version: 1.0 * LastModified: Dec 25 1999 * This library is free. You can redistribute it and/or modify it. */functionUtf8ArrayToStr(array){varout,i,len,c;varchar2,char3;out="";len=array.length;i=0;while(i<len){c=array[i++];switch(c>>4){case0: case1: case2: case3: case4: case5: case6: case7:
// 0xxxxxxxout+=String.fromCharCode(c);break;case12: case13:
// 110x xxxx 10xx xxxxchar2=array[i++];out+=String.fromCharCode(((c&0x1F)<<6)|(char2&0x3F));break;case14:
// 1110 xxxx 10xx xxxx 10xx xxxxchar2=array[i++];char3=array[i++];out+=String.fromCharCode(((c&0x0F)<<12)|((char2&0x3F)<<6)|((char3&0x3F)<<0));break;}}returnout;}
Large blocks
大量数据异步情况
/** * Converts an array buffer to a string * * @param {Uin8} uint8arr | The buffer to convert * @param {Function} callback | The function to call when conversion is complete */functionlargeuint8ArrToString(uint8arr,callback){varbb=newBlob([uint8arr]);varf=newFileReader();f.onload=function(e){callback(e.target.result);};f.readAsText(bb);}// Usage example// "Hello" in Uint8Array formatvarmyuint8Arr=newUint8Array([72,101,108,108,111,32,33]);largeuint8ArrToString(myuint8Arr,function(text){// Helloconsole.log(text);});
The text was updated successfully, but these errors were encountered:
Little strings
少量数据使用超出异常
Browser implementation
浏览器环境使用TextEncoder 和 TextDecoder 原生方法实现,注意兼容性。
Crossplatform method
跨平台依赖性低运行良好
Large blocks
大量数据异步情况
The text was updated successfully, but these errors were encountered: