THE POST BELOW IS MORE THAN 5 YEARS OLD. RELATED SUPPORT INFORMATION MIGHT BE OUTDATED OR DEPRECATED
On 07/01/2006 at 10:43, xxxxxxxx wrote:
The bitwise operators can be a pain in the posterior. Although much can be done with them, my general usages are setting, unsetting, and checking bits.
You know how to set a bunch of bits: FLAG1|FLAG2|FLAG3
Setting individual bits on a variable is similar: flags |= FLAG1. And flags |= (FLAG1|FLAG2).
Unsetting individual bits is strange ('~' is the unary/bitwise 'one's complement') : flags &= ~FLAG1.
Checking bits, as shown in the previously post, is: var & FLAG1. Simply use '!' for inverse checks: if (!(var & FLAG1)). Not fancy, but more intuitive than other possible ways of doing the same.
Bitwise operators are somewhat mysterious, but for coding they are indispensible. For instance, I never do this with integers: a = b / 2 (or any power of 2). Divides are expensive, even when integral. In these cases, best to use the shift operator: a = b >> 1. And you can do multiplication of integers by powers of 2 by going the other way: (a = b << 1) is the same as (a = b * 2).
That's the lesson for today!