Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the function of the ~ bitwise operator (Tilde) [duplicate]

Tags:

Possible Duplicate:
What does this ~ operator mean here?
Bit not operation in PHP(or any other language probably)

Can someone explain me the ~ operator in PHP? I know it's a NOT-operator, but why does PHP convert following statement to the negative value of the variable minus one?

$a = 1; echo ~$a    // echo -2 $a = 2; echo ~$a    // echo -3 $a = 3; echo ~$a    // echo -4   
like image 804
Michiel Avatar asked Feb 03 '12 13:02

Michiel


People also ask

What is tilde in bitwise operator?

The bitwise NOT operator in C++ is the tilde character ~ . Unlike & and |, the bitwise NOT operator is applied to a single operand to its right. Bitwise NOT changes each bit to its opposite: 0 becomes 1, and 1 becomes 0.

What is the purpose of double tilde operator?

The “double tilde” (~~) operator is a double NOT Bitwise operator. Use it as a substitute for Math. floor(), since it's faster.

What is the use of tilde in C?

In C the tilde character is used as bitwise NOT unary operator, following the notation in logic (an ! causes a logical NOT, instead). This is also used by most languages based on or influenced by C, such as C++, D and C#.

What does double tilde mean in JavaScript?

This is a special kind of operator in JavaScript. To understand the double tilde operator, first, we need to discuss the tilde operator or Bitwise NOT. The (~) tilde operator takes any number and inverts the binary digits, for example, if the number is (100111) after inversion it would be (011000).


2 Answers

This is called the two's complement arithmetic. You can read about it in more detail here.

The operator ~ is a binary negation operator (as opposed to boolean negation), and being that, it inverses all the bits of its operand. The result is a negative number in two's complement arithmetic.

like image 156
buc Avatar answered Sep 28 '22 23:09

buc


It's a bitwise NOT.

It converts all 1s to 0s, and all 0s to 1s. So 1 becomes -2 (0b111111111110 in binary representation).

Have a look at the doc http://php.net/manual/en/language.operators.bitwise.php

like image 32
akond Avatar answered Sep 28 '22 23:09

akond