In low-level programming, there are times when you need to set, clear, toggle or check a single bit of a given variable. And, in my case, there are an equal number of times I just can’t remember how to do so! Instead of repeatedly resolving into Stackoverflow I thought I’d write the tricks right here for future reference.
The bitwise operators
& (AND), | (OR), ^ (XOR), ~ (NOT), << (L SHIFT) and >> (R SHIFT) work basically the same in every programming language: I usually come across these problems when writing low-level code in C.
OK, on with the tricks already!
Set bit x of variable num
num |= 1 << x;
Clear bit x of variable num
num &= ~(1 << x);
Toggle bit x of variable num
num ^= 1 << x;
Check value of bit x in variable num
value = (num >> x) & 1;
The last one returns a nonzero value if the bit is set (the value may not be exactly 1), zero otherwise.
And there you have it!