title: C Bit Operation Logic (bitAnd)
body: <p><strong>Background:<br></strong>
  I stumbled across bitwise operators in C <a href="http://www.cprogramming.com/tutorial/bitwise_operators.html" rel="nofollow">here</a>, and now I am trying to learn more about them. I searched around for exercises and came across <a href="http://www.cs.northwestern.edu/~wms128/bits.c" rel="nofollow">this</a>.</p>
  
  <p>However, I'm having trouble understanding the first one "bitAnd."</p>
  
  <p>The code reads:</p>
  
  <pre><code>/* 
   * bitAnd - x&amp;y using only ~ and | 
   *   Example: bitAnd(6, 5) = 4
   *   Legal ops: ~ |
   *   Max ops: 8
   *   Rating: 1
   */
  int bitAnd(int x, int y) {
         /* NOR Equivelent of AND */
    return ~(~x | ~y);
  
  }
  </code></pre>
  
  <p><strong>Question:<br></strong>
  Now, I thought that the pipe ( | ) means "or." So, why do we need ~x and ~y? Can't we just say something like:</p>
  
  <pre><code>int bitAnd(int x, int y) {
      int or = x | y; //something is one number or the other
      int and = ~or; // not or is the same as and
      return and;
  }
  </code></pre>
  
  <p>I wrote and ran the second code sample for myself (I have a main function to run it). I get -8 as the answer, but with values 6 and 5, you should get 4. 
  If you have something for "or" (the pipe operator) and "and" is just the opposite or, why do we need to use "~" on each value before we calculate ~and?</p>
  
  <p><strong>Some extra information/thoughts:<br></strong>
  I understand that "~" flips all the bits in the value. "Or" copies the bit from either value into the other if it exists (I learned that from <a href="http://www.tutorialspoint.com/ansi_c/c_bits_manipulation.htm" rel="nofollow">here</a>). So, if I have:</p>
  
  <p>6 = 00000110 <br>
  and <br>
  5 = 00000101
  I should get 0000111.</p>
  
  <p>I only mention that to show what knowledge I have of some of the operations in case my understanding of those are wrong as well.</p>