How to efficiently read bits out of bytes?

前端 未结 4 1913
野的像风
野的像风 2021-01-02 02:24

I\'m working on a project that includes WebSockets, and data between the server (Node.js) and the client (Chrome) is sent using a custom (very simple) format for data exchan

4条回答
  •  孤城傲影
    2021-01-02 03:07

    function byte2bits(a)
    {
        var tmp = "";
        for(var i = 128; i >= 1; i /= 2)
            tmp += a&i?'1':'0';
        return tmp;
    }
    function split2Bits(a, n)
    {
        var buff = "";
        var b = [];
        for(var i = 0; i < a.length; i++)
        {
            buff += byte2bits(a[i]);
            while(buff.length >= n)
            {
                b.push(buff.substr(0, n));
                buff = buff.substr(n);
            }
        }
        return [b, buff];
    }
    var a, b, r;
    a = [227, 142];
    [b, r] = split2Bits(a, 3);
    //b = ["111", "000", "111", "000", "111"];
    //r = '0'; //rest of bits
    

提交回复
热议问题