I use a byte to store some flag like 10101010, and I would like to know how to verify that a specific bit is at 1 or 0.
I use a byte to store some flag like 10101010 , and I would
Share
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.
Here’s a function that can be used to test any
bit:Explanation:
The left shift operator
<<creates a bitmask. To illustrate:(1 << 0)equals00000001(1 << 1)equals00000010(1 << 3)equals00001000So a shift of
0tests the rightmost bit. A shift of31would be the leftmost bit of a 32-bit value.The bitwise-and operator (
&) gives a result where all the bits that are1on both sides are set. Examples:1111 & 0001equals00011111 & 0010equals00100000 & 0001equals0000.So, the expression:
will return the bitmask if the associated bit (
bitindex) contains a1in that position, or else it will return0(meaning it does not contain a1at the assoicatedbitindex).To simplify, the expression tests if the result is greater than
zero.Result > 0returnstrue, meaning the byte has a1in the testedbitindexposition.falsemeaning the result was zero, which means there’s a0in testedbitindexposition.Note the
!= 0is not required in the statement since it’s a bool, but I like to make it explicit.