I’m trying to know the states of different bits over a char
Let’s say I’ve:
char a = 11 //00001011 in binary
How can I retrieve bit number 5 which is currently 0 and cast it to a bool variable? And how can I set it?
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.
As you’ve noted:
Since you said the
bit number 5is clear right now, let’s *define the position of the bits as you’re talking about them:You want to test the 5th bit, that means you need a mask that accesses the fifth bit, here’s some masks:
To set your bit you need a bit-wise OR (|)
To test the bit we can use the bit-wise AND (&)
*it was pointed out that this is a 1-based indexing as opposed to the more typical 0-based indexing. Which is true. Based on the description I chose to read the question as “bit number 5” meaning typical (human) based counting of 1, 2, 3, 4, etc out of 8-bits.
If you’d rather use a 0-based indexing, this is no problem, just “shift” the same logic by one, the mask for the “5th” bit in 0-based indexing is
0x20When talking about bits it’s good to note which is the least significant bit, and 0 or 1 based to be totally clear.