Extracting bits using bit manipulation

后端 未结 2 689
灰色年华
灰色年华 2021-01-22 21:34

I have a 32-bit unsigned int and I need to extract bits at given positions and make a new number out of those bits. For example, if I have a 0xFFFFFFFF and want bits 0,10,11 my

2条回答
  •  半阙折子戏
    2021-01-22 22:31

    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.

提交回复
热议问题