#1,109 – The Bitwise NOT Operator

You can use the ~ operator to do a bitwise NOT operation on an integer-based value.

A NOT operation is applied to a single input bit, returning true if the input bit is false, or false if it is true.  The NOT operator “flips” or “negates” the input bit.  Here is a truth table showing the output value for the possible input values.

  • ~0  = 1
  • ~1 = 0

You can use the ~ operator on an arbitrary integer value as shown below.  The NOT operation will be applied to the integer value, one bit at a time.

            int n = 5;
            int result = ~n;
            Console.WriteLine("~{0} = {1}", n, result);

It may help to use hex notation in order to better understand how the NOT operation works on each bit.

            int n = 0x00000005;
            int result = ~n;
            Console.WriteLine(  "~{0:X8} = {1:X8}", n, result);