### The bit-wise operators in C

• Bit level operators

• Bit level operation:

 A bit with value 1 represents the logical value true A bit with value 0 represents the logical value false Operation is performed on a series of bit by performing the operation on one bit at a time

• Examples:

 ``` Bitwise AND: 00010100 (0 AND 0 = 0 0 AND 1 = 0) 00001111 (1 AND 0 = 0 1 AND 1 = 1) -------- 00000100 Bitwise OR: 00010100 (0 OR 0 = 0 0 OR 1 = 1) 00001111 (1 OR 0 = 1 1 OR 1 = 1) -------- 00011111 Bitwise XOR: 00010100 (0 XOR 0 = 0 0 XOR 1 = 1) (exclusive OR) 00001111 (1 XOR 0 = 1 1 XOR 1 = 0) -------- 00011011 Bitwise NOT: 00010100 (NOT 0 = 1 NOT 1 = 0) -------- 11101011 ```

• Bitwise operators of C

• Bitwise operators:

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

• Example program:

 ``` int main( int argc, char* argv[] ) { char a = 20; /* 00010100 = 16 + 4 = 20 */ char b = 15; /* 00001111 = 8 + 4 + 2 + 1 = 15 */ printf( "a & b = %d\n", (a & b) ); printf( "a | b = %d\n", (a | b) ); printf( "a ^ b = %d\n", (a ^ b) ); printf( "~ a = %d\n", (~ a) ); } ```

Output: (Note: the "%d" conversion character will output the bit expressions as a decimal number representation)

 ``` a & b = 4 ( 4 = 00000100 ) a | b = 31 ( 31 = 00011111 ) a ^ b = 27 ( 27 = 00011011 ) ~ a = -21 ( -21 = 11101011 --- this is 2'c complement code for signed numbers ! ) ```

(I have added the convertion of the decimal number into bits between brackets for your viewing convenience)