I'm trying to learn how to use bitwise operators on a given input but am not having much luck figuring out how to use them.
Let's say I have this following octet:
11(01)0000
How would I extract the bits between the braces?
You need to:
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)0000are 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.
11in binary, i.e.3in 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.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.
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
来源:https://stackoverflow.com/questions/8408918/extracting-bits-with-bitwise-operators