Bit level operations

  • Arithmetic operations (such as +, −, *, /) operates on the codes

    Example:

       int x, y;
    
       Then:    x + y    adds  2s complement codes
    

    We have made computer circuits that can add 2s complement codes (for details: take CS355)


  • Bit level operations in contrast, will operate on each bit individually.

  • Meaning of bit values used in bit level operations:

      • A bit with value 1 represents the logical value true

      • A bit with value 0 represents the logical value false

The bitwise AND operation

  • The AND operation using 1 bit is as follows:

       0 AND 0 = 0       1 AND 0 = 0
       0 AND 1 = 0	     1 AND 1 = 1 

  • The AND operation appied on an 8 bits value is as follows:

            00010100
       AND  00001111 
      ---------------
            00000100  <--- result of 00010100 AND 00001111 

    The result is obtained by performing the AND operation on each pair of bits individually

The bitwise OR operation

  • The OR operation using 1 bit is as follows:

       0 OR 0 = 0       1 OR 0 = 1
       0 OR 1 = 1       1 OR 1 = 1 

  • The OR operation appied on an 8 bits value is as follows:

            00010100
        OR  00001111 
      ---------------
            00011111  <--- result of 00010100 OR 00001111 

    The result is obtained by performing the OR operation on each pair of bits individually

The bitwise XOR operation

  • The XOR operation using 1 bit is as follows:

       0 XOR 0 = 0       1 XOR 0 = 1 (exactly one input value = 1)
       0 XOR 1 = 1       1 XOR 1 = 0 

  • The XOR operation appied on an 8 bits value is as follows:

            00010100
       XOR  00001111 
      ---------------
            00011011  <--- result of 00010100 XOR 00001111 

    The result is obtained by performing the XOR operation on each pair of bits individually

The bitwise NOT operation

  • The NOT operation using 1 bit is as follows:

       NOT 0 = 1         NOT 1 = 0
    

  • The NOT operation appied on an 8 bits value is as follows:

       NOT  00001111 
      ---------------
            11110000  <--- result of NOT 00001111 

    The result is obtained by performing the NOT operation on each pair of bits individually

The bitwise operators in C

  • The bitwise operators of C (also available in Java):

      Operator symbol Meaning
      &   Bitwise AND
      |   Bitwise OR
      ^   Bitwise XOR
      ~   Bitwise NOT

  • Sample C program:

    int main( int argc, char* argv[] )
    {
       char a = 20;         //     00010100 ==> 16 + 4 = 20       
       char b = 15;         //     00001111 ==> 8 + 4 + 2 + 1 = 15
       char c;
    
       c = a & b;           // c = 00000100
       c = a | b;		// c = 00011111
       c = a ^ b;		// c = 00011011
       c = ~a;              // c = 11101011
    } 

DEMO: demo/C/set1/bit-op1.c