| Bit operations: Test a bit | |||||||||||||
| Problem: given int i, is bit n set (equal to 1)? | |||||||||||||
| bn | b0 | ||||||||||||
| i | 0000 | 0000 | 0000 | 0000 |
|
0000 | 0000 | 0010 | |||||
| bit n | |||||||||||||
| How can we test if this bit is 1? | |||||||||||||
| We can use & operator with a "mask" variable: | |||||||||||||
| mask | 0000 | 0000 | 0000 | 0000 |
|
0000 | 0000 | 0000 | |||||
| if (i & mask) | |||||||||||||
| printf ("yes"); | |||||||||||||
| else | |||||||||||||
| printf ("no"); | |||||||||||||
| What is the problem with this? | |||||||||||||
| We would need 32 different masks, depending on the value of n! | |||||||||||||
| Answer: | |||||||||||||
| i & (1 << n) | /* idiom */ | ||||||||||||
| or | |||||||||||||
| (i >> n) & 1 | (Shift nth bit to first location, compare to mask of 1) | ||||||||||||