0

I'am trying to understand how making an addition of two negative numbers in PHP 7.1. So, I read these questions in stackeoverflow:

I tested this script:

<?php 
 echo (~5) + (~7); // output: -14

But I don't understand why the result is -14. Tying to solve manually, I did like this:

~5 => (1011)
~7 => (1001)

(1011) + (1001) = 0100 => 8 != -14 the output of php script

Where is the error?

Community
  • 1
  • 1
Houssem ZITOUN
  • 644
  • 1
  • 8
  • 23

1 Answers1

0

After reading few examples in php.net I fond a very good demonstration:

The NOT or complement operator ( ~ ) and negative binary numbers can be confusing.

~2 = -3 because you use the formula ~x = -x - 1 The bitwise complement of a decimal number is the negation of the number minus 1.

NOTE: just using 4 bits here for the examples below but in reality PHP uses 32 bits.

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.

source from php.net

Houssem ZITOUN
  • 644
  • 1
  • 8
  • 23