liv2hak
liv2hak

Reputation: 14970

bit masks and shift operator

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.?

Upvotes: 1

Views: 2346

Answers (4)

Ry-
Ry-

Reputation: 224856

The right shift by 12 isn't necessary, but it's nice because you can compare it with 1 instead of 4096 (harder to remember and to tell exactly what the code is doing) but since you've got BIT12 there already it's OK to use that instead.

Upvotes: 1

mjv
mjv

Reputation: 75095

It is unecessary

if (reg_val & BIT12)   // would be sufficient
{
     //DO SOMETHING.
}

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

if ((reg_val & BIT12) == BIT12)  
{
     //DO SOMETHING.
}

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.

Upvotes: 7

gatkin
gatkin

Reputation: 1912

You could certainly write if (0 != reg_val & BIT12) ... or if (BIT12 == reg_val & BIT12) ...

Upvotes: 1

littleadv
littleadv

Reputation: 20262

The right shift is necessary because the result of the & will be 1<<12, and you're comparing to 1 which is 1<<0.

Instead of comparing to 1, you can compare to not 0 (i.e.: 0 !=...), and then skip the right shift.

Upvotes: 2

Related Questions