Bitwise ComplementApply the complement operator and learn more about bitwise operations.
This page was last reviewed on Jul 27, 2021.
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.
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.
Binary Representation
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); } }
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.
Set Bit
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jul 27, 2021 (image).
© 2007-2023 Sam Allen.