Extracting bits with bitwise operators [closed]

萝らか妹 提交于 2019-12-02 08:26:26

You need to:

  1. create a suitable mask with ones only where are the bytes you need (you just need to write the number in binary and convert to e.g. hex to put it inside the C program). The parentheses in your 11(01)0000 are your indication to where to put the ones in your mask.

    Alternatively, create a mask made of as many ones as the chunk of bits you are interested in (in your case two ones, i.e. 11 in binary, i.e. 3 in decimal) and left shift it to move it to the position where you need it (left shift operator: <<). This approach can be useful if the position of your "bit window" is known only at runtime.

  2. Perform a bitwise-and operation between your number and the mask (the bitwise and operator is &).

    The bitwise and only leaves as 1 the bits that are 1 in both the operands, so the effect is "filtering" the source number with the bits of the mask: only the bits that correspond to ones in the mask are let "flow through" it, all the other bits are left as zero.

  3. Now you have extracted the bits of your interest, but they are still in their original position inside the number. If you want/need it, you can then right shift them to "align them to the right" (use the right shift operator: >>).

Mask your value with the bits you want to select, and shift.

If your 11010000 number is x, the two bit number you want is

(x & 0x30 ) >> 4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!