计算php中两个负二进制数的和 7.1

Calculating sum of two negative binary numbers in php 7.1

我想了解如何在 PHP 7.1 中添加两个负数。所以,我在 stackeoverflow 中阅读了这些问题:

我测试了这个脚本:

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

但是我不明白为什么结果是-14。想手动解决,我是这样的:

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

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

哪里出错了?

阅读 php.net 中的几个示例后,我发现了一个非常好的演示:

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