How to efficiently read bits out of bytes? How to efficiently read bits out of bytes? node.js node.js

How to efficiently read bits out of bytes?


The binary AND and bit shifting operations are the fastest way of doing this. They translate well into machine code instructions. The only way to further speed this up is by sacrificing bandwidth for speed by for example simply not using more than 3 bits per byte, but judging from your question you've probably already considered and rejected that tradeoff.


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


if endian-ness is taken care, you can access it as an int or a long int array. There is another possibily of not using bit 3 and bit 7