Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the function of the ~ operator?

Tags:

c++

c

operators

c#

Unfortunately, search engines have failed me using this query.

For instance:

int foo = ~bar;
like image 942
Lazlo Avatar asked Sep 15 '09 21:09

Lazlo


2 Answers

In C and C++, it's a bitwise NOT.

like image 173
John Millikin Avatar answered Oct 12 '22 23:10

John Millikin


I'm assuming based on your most active tags you're referring to C#, but it's the same NOT operator in C and C++ as well.

From MSDN:

The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, long, and ulong.

Example program:

static void Main() 
{
    int[] values = { 0, 0x111, 0xfffff, 0x8888, 0x22000022};
    foreach (int v in values)
    {
        Console.WriteLine("~0x{0:x8} = 0x{1:x8}", v, ~v);
    }
}

Output:

~0x00000000 = 0xffffffff
~0x00000111 = 0xfffffeee
~0x000fffff = 0xfff00000
~0x00008888 = 0xffff7777
~0x22000022 = 0xddffffdd
like image 29
John Rasch Avatar answered Oct 12 '22 23:10

John Rasch