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