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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
>>).