Assume that a logical operation can only return a single true or false. That's what happens when you do a comparison test for example.
A < B
as an expression returns a true or false based on the values of A and B. You'd do a logical
and or
or when testing whether two or more of these comparisons are true or not.
if (A < B && C > D) {....}
This means that for the statements in the braces to happen A must be less than B AND C must be greater than D) If you used ||
if (A < B || C > D) {....}
then either A can be less and B or C can be greater than D and the statement will be executed. For it to fail, both must be false.
A bitwise AND or OR matches up the bit position of larger bit patterns. Often an integer or other numeric type is used to store a collection of single bits that aren't intended to necessarily be related.
Let's say you have two true/false on/off conditions you want to track. I'll use an 8 bit variable for this for brevity.
UINT8 MachineStatus = 0;
and it would look like this initially.
00000000
Let's say you want to track if the machine is on or of and if there's a warning condition. We'll use the least significant bit tell us if the machine is on or off and the next LSB to tell us if there's a warning condition. For now we'll assume that some other part of the program sets these and all we want to do is test them.
#define MACHINE_ON 1;
#define MACHINE_WARNING 2;
These represent bit positions 00000001 and 00000010 respectively.
To test if the machine is on we can do
if (MachineStatus & MACHINE_ON) {....}
what this does is matches up the bit position of the two numbers
00000001 MachineStatus
00000001 MACHINE_ON (mask)
--------
00000001 result of anding
by anding these together we're saying if both bit positions are 1 (true) the result for that bit position is true. If either zero then the result for that bit position is zero.
if we bitwise or them then either bit position can be 1 and the matching result bit is 1. Both of them have to be zero (false) for that position to be zero in the result. That's how we set bits in a result by making the bit position in the mask equal to zero.
MachineStatus = MachineStatus | MACHINE_ON;
sets the first bit on. We can also short hand this with
MachineStatus |= MACHINE_ON.
Lilith, Night Butterfly
I'm not a programmer but I play one in the office