Bitwise Operators
K&R gives detailed description of the behaviours of these operators but since I don’t how moving bits can be useful I have to memorise those rules. It’s only when I was reading The Linux Programming Interface that the whole thing began to make sense to me.
While most books and websites focus on behaviours, simply telling you what you will get when you apply a bitwise operator on two integers, this is a whole other story when you are dealing with the Linux/Unix programming interface, and you will often find yourself using bitwise operators to set flags rather than calculate integers. So instead of meaningless integers 5&9
you can now see bits like 0001
and 1000
as options, flags or switches.
// & to turn off some switches
0000// | to turn on more switches
1001// ^ to toggle switches
1001// ~a to toggle switches (unary)
1110
Since these are all switches and flags, we certainly don’t want to memorise these bit patterns and therefore we give them names like
#define OPTION_1 (1<<0)
#define OPTION_2 (1<<1)
#define OPTION_3 (1<<2)
#define OPTION_4 (1<<3)
#define OPTION_5 (1<<4)
#define OPTION_6 (1<<5)
#define OPTION_7 (1<<6)
#define OPTION_8 (1<<7)
And with that we can do something like
decision |= OPTION_1 | OPTION_2; // previous plus option 1 and 2
decision &= ~OPTION_2; // turn off option 2
(decision & OPTION_2) > 0 // check if option 2 is on
decision ^= OPTION_2 // toggle option 2
That’s it, and I hope bitwise operations now become more natural to you (and if it still doesn’t make sense, why not just try bit-fields first). More on this can be found in this blog post.