Oh my... just wait till chapter 7 ... Just kidding. Bitwise operations are probably the most confusing part of any programming language. Worse than pointers, in my opinion...
Originally Posted by roelof
The first thing you need is "truth tables" for the various functions... and yes, these are largely derived from logic gates AND OR NOT and XOR... so they're actually pretty easy once you get the concept.
For simplicity lets envision a logic "blob" with 2 inputs A and B and 1 output...
For an AND situation A and B both have to be TRUE (1) before the output is TRUE ... if output is FALSE if either A or B or both are FALSE.
For an OR situation if either or both of A or B is TRUE the output is TRUE... for the output to be FALSE both A and B must be FALSE.
For an XOR situation if either A or B is true the output is TRUE... the output will be false if A and B are both FALSE or A and B are both TRUE.
Now lets picture 8 of these things stacked up beside each other being fed by bytes from the computer...
This is based on ANDing, ORing or XORing, the individual bits in the bytes. (Of course it works on any integer type variable)
A = 1 0 1 1 1 0 0 1
B = 1 1 1 0 1 1 0 0
AND = 1 0 1 0 1 0 0 0
OR = 1 1 1 1 1 1 0 1
XOR = 0 1 0 1 0 1 0 1
The most common use is in bit filtering to apply various flags or eliminate unwanted elements from a variable. For example:
Bit shifting is a bit strange but far simpler... Here you need to picture a clear plastic tube with 7 white balls and one red one... If you put a new white ball in the left end you push everything to the right, effectively moving the red ball over one space... Same from the other end, except now it moves one position left...
// is a number odd?
int b = A & 1; // b = 0 or 1, lowest bit is always 1 for an odd number
// make a number odd
int b = A | 1; // set the lowest bit on.
// flip even and odd
int b = A ^ 1; // toggle the lowest bit
// merge two bytes in a short int.
char A = 0xABAD;
char B = 0xC0DE;
short C = A << 8; //move A over 8 positions left and assign it to C
C += B; // add the value of B to C.
// C = ABADCODE
Does that help?