This operation changes all bits—it turns 0 into 1 and 1 into 0. The character "~" denotes the complement operator. It affects every bit in the value you apply it to.
This operator is often used in combination with other bitwise operators. It inverts each bit, and is often used with a mask.
GetIntBinaryString()
uses logic to display all the bits in an integer as 1 or 0 characters. The integer value is set to 555, and this bit configuration is printed.
using System; class Program { static void Main() { int value = 555; Console.WriteLine("{0} = {1}", GetIntBinaryString(value), value); value = ~value; Console.WriteLine("{0} = {1}", GetIntBinaryString(value), value); value = ~value; Console.WriteLine("{0} = {1}", GetIntBinaryString(value), value); } static string GetIntBinaryString(int value) { return Convert.ToString(value, 2).PadLeft(32, '0'); } }00000000000000000000001000101011 = 555 11111111111111111111110111010100 = -556 00000000000000000000001000101011 = 555
The bitwise complement operator is rarely useful. But if you use the operator with the bitwise "AND" and also the shift operator, you can set bits to zero in an integer.
This example program demonstrated the low-level effect of using the bitwise complement "~" operator in the C# language, and also how to use its syntax.