2020-09-03

tech2023-06-27  149

js  ArrayBuffers和字符串相互转换

/** * 将ArrayBuffer转换为string * @param input 需要被转换的ArrayBuffer */ public static ab2str(input: ArrayBuffer): string { var binary = ''; var bytes = new Uint16Array(input); var len = bytes.byteLength; for (var i = 0; i < len; i++) { binary += String.fromCharCode(bytes[i]); } return unescape(binary); } /** * 将string转换为ArrayBuffer * @param input 需要被转换的string */ public static str2ab(input: string): ArrayBuffer { input = escape(input); var buf = new ArrayBuffer(input.length * 2); // 2 bytes for each char var bufView = new Uint16Array(buf); for (var i = 0, strLen = input.length; i < strLen; i++) { bufView[i] = input.charCodeAt(i); } return buf; }

 

最新回复(0)