TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Bitwise Complement

This C# example program demonstrates the results of applying the complement operator.

Bitwise complement 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. It is often used in combination with other bitwise operators.

Example. First, this program introduces the GetIntBinaryString method, which uses some logic to visually display all the bits in an integer as 1 or 0 characters. Then, the integer value is zero to 555, and this bit configuration is printed.

Next, we apply the bitwise complement operator to the integer. All the bits that were 0 are flipped to 1, and all bits that were 1 are flipped to 0. Finally, the bitwise complement operator is used again, reversing the effect.

Binary Representation

C# program that uses bitwise complement

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 n)
    {
	char[] b = new char[32];
	int pos = 31;
	int i = 0;

	while (i < 32)
	{
	    if ((n & (1 << i)) != 0)
		b[pos] = '1';
	    else
		b[pos] = '0';
	    pos--;
	    i++;
	}
	return new string(b);
    }
}

Output

00000000000000000000001000101011 = 555
11111111111111111111110111010100 = -556
00000000000000000000001000101011 = 555

Set bits to zero. The bitwise complement operator is not useful in many programs. But if you use the operator with the bitwise "AND" and also the shift operator, you can set bits to zero in an integer.

Note: This means you can use integers as an array of boolean values. This representation is much more compact in memory.

Set Bit to Zero

Summary. 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. This operator is not useful in many real-world programs.

But: The complement operator can come in handy when using integers as arrays of boolean flags.

Int