2020-09-03

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;
    }

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页