I have a question regarding bit masks and shift operator in C
uint32_t reg_val = 0xffffffff;
if(1 == ((reg_val & BIT12)>>12))
{
//DO SOMETHING.
}
where BIT12 is (1 <<12).
The question is whether the right shift by 12 is really necessary.If not is it because the logical value of the expression (reg_val&BIT12) is ‘1’ if BIT12 is set in reg_val and ‘0’ if BIT12 is cleared in reg_val?Also is it a recommended coding practice to do the shift from a readability point of view.?
It is unecessary
Now, the above works because BIT12 is assumed to have only one non-zero bit . A more generic way to handle this kind of test would be
The reason for this is that the first snippet only tests if reg_val AND-ed with BIT12 is non-zero (i.e. reg_val and BIT12 have at least one non-zero bit in common). The second snippet tests that all the bits which are set in BIT12 are also set in reg_val.