28

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  
Community
  • 1
  • 1
Michiel
  • 7,855
  • 16
  • 61
  • 113
  • Information about this is available _all over the internet_ – Lightness Races in Orbit Feb 03 '12 at 14:03
  • 4
    In the duplicate, there's nothing related to the two's complement arithmetic, which is the essence of this question. I doubt it is an _exact_ duplicate. However, this [this question](http://stackoverflow.com/q/8785054/509303) covers exactly the same problem. – buc Feb 03 '12 at 14:12

3 Answers3

33

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.

buc
  • 6,268
  • 1
  • 34
  • 51
6

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

Mr.Web
  • 6,992
  • 8
  • 51
  • 86
akond
  • 15,865
  • 4
  • 35
  • 55
  • 2
    -2 indeed. Just checked. – akond Feb 04 '12 at 18:12
  • It is true. It is bitwise NOT, but signed numbers representation makes the to show as ie,. -2. But if you look at binary level you will see it is completely a negation. – Seyfi Jul 31 '16 at 21:33
4

~ flips all the bits of the number. In two's complement (google it), mathematical negation is achievable by flipping all the bits and then adding 1. If you only do the first step (ie: just flip the bits), you have the additive inverse minus 1.

cHao
  • 84,970
  • 20
  • 145
  • 172