I hope this explaination will help somewhat:
Sometimes the bits of an int are used to flag some states, e.g. if an item is available and such.
There are roughly two cases to handle:
* Extracting a single bit from a bit-field, and
* setting a single bit in a bit field,
Let's assume you have a char value as bit-field (char consists of 8 bits) and you want to know what the fifth bit of this field states.
Then you create a bit-mask which depresses all other bits then the fifth.
The mask for the fifth bit would look: 0b00010000
If you conjunct this mask via bitwise 'and' operator , you depress all other bits then the fifth.
The evaluation of this conjunction will ether be 0b00000000 if the fifth bit was zero, or 0b00010000 if the fifth bit was 1.
Here an example how to code such:
1 2
|
char bit_mask = 0b00010000;
bool is_fifth_bit_set = (bool)(my_bit_field & bit mask);
|
If you want to set a single bit in a bit field, you need to conjunct this bit via bitwise 'or'. Before doing that you have to place this bit at the correct place within the bit mask (via shift-operator).
Here an example how to set the fifth bit of the bit field.
1 2 3 4
|
bool my_flag; // represents a single bit, whereby 'false' represents 0, and 'true' represents 1
... // set my_flag to true or false
char bit_mask = (char)my_flag << 4; // shifts the bit at the fifth place
my_bit_field = my_bit_field | bit mask; // conjuncts the bit field via bitwise 'or'
|
If it's still unclear how the bit mask work, I suggest that you comprehend some examples by yourself using paper and pen.