Bit Manipulation: Logical Operations

It’s important never to get bitwise operations mixed up with logical operations, which is easier said than done given their similarities. Just like in C++, the logical AND operator is &&, the logical OR operator is ||, and the logical NOT operator is !. At its core, the two sets of operations functions are similar, but the key difference lies in their inputs and outputs. Bitwise operations work with the individual bits of a bitstring, whereas logical operations treats the bitstrings as booleans.

In C, a bitstring that evaluates to 0 is considered false. Anything else is considered true (though, in evaluating boolean expressions, C will return 1 for true). To demonstrate how critical it is to never get these sets of operations mixed up, let us take two different bitstrings 11110000 and 00001111. If we do bitwise operations, then 11110000 (true) & 00001111 (true) = 00000000 (false). Logically, true AND true does not equal false, so bitwise operations are not a good substitute for logical operations. Similarly, if we do logical operations, then 00000000 (false) || 11010011 (true) = 00000001 (true). In this case, Bit 0 was set to 1, but other bit in the first bitstring remained unchanged. Thus, bitwise operations can’t substitute logical operations. So if you’re writing C code, and you notice that your conditionals aren’t evaluating properly, check to make sure you are using logical operations and not bitwise operations. Although you can get lucky with mismatched operations sometimes, there is no guarantee that it will always work.