Я пытаюсь понять, как сложить два отрицательных числа в 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
Где ошибка?
Вы имели в виду иметь символ минус -? У вас тильда ~
Возможный дубликат Какова функция побитового оператора ~ (тильда)
@u_mulder Итак, ~ 5 = (1011) = -6 и ~ 7 = (1001) = -8?
Я не понимаю, откуда взялся 1011, насколько я знаю, 5 - это 101, инвертирование 0 в 1 и наоборот дает вам как минимум 1........010 в зависимости от вашего компьютера (32 или 64 бит).
Мой компьютер 64-битный, и мне понравилось это: 5 = (0101) => ~ 5 = (1011)






Прочитав несколько примеров в 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.
Потому что
~5- это-6, а~7- это-8.