Lazlo
Lazlo

Reputation: 8770

What is the function of the ~ operator?

Unfortunately, search engines have failed me using this query.

For instance:

int foo = ~bar;

Upvotes: 6

Views: 2351

Answers (8)

MiffTheFox
MiffTheFox

Reputation: 21565

In most C-like languages, it is a bitwise not. This will take the raw binary implementation of a number, and change all 1's to 0's and 0's to 1's.

For example:

ushort foo = 42;   // 0000 0000 0010 1010
ushort bar = ~foo; // 1111 1111 1101 0101
Console.WriteLine(bar); // 65493

Upvotes: 0

John Rasch
John Rasch

Reputation: 63435

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

Upvotes: 11

Stephen Van Dahm
Stephen Van Dahm

Reputation: 101

In C, it's the bitwise complement operator. Basically, it looks at the binary representation of a number and converts the ones into zeros and the zeros into ones.

Upvotes: 0

Remus Rusanu
Remus Rusanu

Reputation: 294227

bitwise negation, yields the bitwise complement of the operand.

In many programming languages (including those in the C family), the bitwise NOT operator is "~" (tilde). This operator must not be confused with the "logical not" operator, "!" (exclamation point), which in C++ treats the entire value as a single Boolean—changing a true value to false, and vice versa, and that C makes a value of 0 to 1 and a value other than 0 to 0. The "logical not" is not a bitwise operation.

Upvotes: 3

Roee Adler
Roee Adler

Reputation: 33980

It's called Tilde (for your future searches), and is usually user for bitwise NOT (i.e. the complement of each bit)

Upvotes: 3

bruno conde
bruno conde

Reputation: 48265

Normally it's the Negation operator. What is the Language?

Upvotes: 1

job
job

Reputation: 9253

It's called a tilde and it looks like some languages use it as a bitwise NOT: http://en.wikipedia.org/wiki/Tilde#Computer_languages

Upvotes: 1

John Millikin
John Millikin

Reputation: 200756

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

Upvotes: 12

Related Questions