I have a 32 bit int I can only access it 8 bits at a time. I need to find out if every even bit is set to 0 and return 0 if its true and 1 otherwise.
So far I am goi
OK, so you've created a bit mask. (01010101)
if ((value & bit_mask) == bit_mask)
then you know that each bit that was set in bit_mask
is also set in value
.
You want to check if every second bit is set to 0. (Not set to 1, as my incorrect answer above checks for)
There are two equally valid approaches: We make the bit mask the opposite (10101010)
Then use the OR operator:
if ((value | bit_mask) == bit_mask)
This checks that each bit that was zero in the bit_mask
is zero in value
.
The second approach is to make the bit mask the same (01010101) and use the AND operator:
if ((value & bit_mask) == 0)
This checks that each bit that is one in the bit_mask
is zero in value
.