Extracting bits using bit manipulation

梦想的初衷 提交于 2019-12-02 02:57:17

Since you are picking off individual bits, there's no reason to make the bit mask a variable; just shift the desired bit into the units bit, and use a mask of 1. E.g.:

...
result = (2*result) | ((bytes >> positions[i]) & 1);
...

Many compilers generate the same code for 2*result and result<<1, so use whichever you like.

Note, if you are designing the interface and don't have good reasons for using short integers for positions[] and count as you do, then don't. Be consistent and specify all the integers the same way.

Beware, untested code:

for(i = 0; i < count; i++) 
{
    bitmask = 1 << positions[i];
    bit = (bytes & bitmask)!=0;
    result = (result << 1)|bit;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!