avasin
avasin

Reputation: 9726

Why negation of number (~ operator) in php gives such strange results?

I tried to perform following code and got strange results:

echo ~1; // gives -2
echo ~2; // gives -3

Perhaps there is a bit, describing if number is positive or negative?

Upvotes: 1

Views: 1328

Answers (2)

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4142

there is no magic or strange output but its comes from the definition of negation

The bitwise complement of a decimal number is the negation of the number minus 1

Its from manual :-

Converting a negative decimal number (ie: -3) into binary takes 3 steps :-

  • 1) convert the positive version of the decimal number into binary (ie: 3 = 0011)

  • 2) flips the bits (ie: 0011 becomes 1100)

  • 3) add 1 (ie: 1100 + 0001 = 1101)

You might be wondering how does 1101 = -3. Well PHP uses the method "2's complement" to render negative binary numbers. If the left most bit is a 1 then the binary number is negative and you flip the bits and add 1. If it is 0 then it is positive and you don't have to do anything. So 0010 would be a positive 2. If it is 1101, it is negative and you flip the bits to get 0010. Add 1 and you get 0011 which equals -3.

Upvotes: 6

Martin
Martin

Reputation: 2028

The operator ~ computes the two's-complement of a number.

You can find more information about what is the two's complement and how to compute it on wikipedia.

Upvotes: 1

Related Questions