How to get binary string from ArrayBuffer?

前端 未结 4 2103
眼角桃花
眼角桃花 2020-12-08 06:03

What is the way to obtain binary string from ArrayBuffer in JavaScript?

I don\'t want to encode the bytes, just get the binary representation as String.

Tha

4条回答
  •  不思量自难忘°
    2020-12-08 06:13

    This will give you a binary string from a typed array

    var bitsPerByte = 8;
    var array = new Uint8Array([0, 50, 100, 170, 200, 255]);
    var string = "";
    
    function repeat(str, num) {
        if (str.length === 0 || num <= 1) {
            if (num === 1) {
                return str;
            }
    
            return '';
        }
    
        var result = '',
            pattern = str;
    
        while (num > 0) {
            if (num & 1) {
                result += pattern;
            }
    
            num >>= 1;
            pattern += pattern;
        }
    
        return result;
    }
    
    function lpad(obj, str, num) {
        return repeat(str, num - obj.length) + obj;
    }
    
    Array.prototype.forEach.call(array, function (element) {
        string += lpad(element.toString(2), "0", bitsPerByte);
    });
    
    console.log(string);
    

    Output is

    000000000011001001100100101010101100100011111111
    

    On jsfiddle

    Or perhaps you are asking about this?

    function ab2str(buf) {
        return String.fromCharCode.apply(null, new Uint16Array(buf));
    }
    

    Note: that using apply in this manner means that you can hit the argument limitation (some 16000 elements or so), and then you will have to loop through the array elements instead.

    On html5rocks

提交回复
热议问题