@rm84co, a mask is an object people use to hide parts of their faces (or all of it). By analogy, a bit mask is a set of bits used to hide (or change) another set of bits.
When you use AND operation, if one of the operands is 1, the result will be the other operand... Example: 1 and 0 = 0, 1 and 1 = 1.
If one of the operands is 0, the result is always zero: 0 and 0 = 0, 0 and 1 = 0... So bit bit is masked.
You can use AND to isolate individual bits. for instance, if I want to know only the value of bit 0, masking all the other bits, I can do:
Here, y will have all its bits zeroed, except bit 0. Bit 0 will be a copy of x's bit 0.
If you want to mask all the bits, except bit 2, for example, you can do:
Because 4 is 0b000...00000100. The mask has only bit 2 set... To simplify you can do something like this:
The (1 << 2) will set the appropriate bit and it is a constant.
Knowing this you could write a code like this to show all the bits, individually, of an integer:
Code:
void show_int_bits( int x )
{
// We'll print all bits of x.
unsigned int bit_count = 8 * sizeof x;
// will mask all bits, except the highest.
unsigned int bit_mask = 1U << (sizeof(int)*8 - 1);
while ( bit_count-- )
{
// (x & bit_mask) will be 0 if higherst bit of x is 0
// or will be different from 0 if highest bit of x is 1.
putchar( x & bit_mask ? '1' : '0' );
// shift all bits to the left, 1 step.
x <<= 1;
}
}
Got it?