Bitwise complement. 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.
Complement info. This operator is often used in combination with other bitwise operators. It inverts each bit, and is often used with a mask.
Example. 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.
Info We apply the bitwise complement operator. 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. We write the results to the console.
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
Set bits to zero. 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.
Note This means you can use integers as an array of boolean values. This representation is much more compact in memory.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 20, 2024 (edit).