Bit not operation in PHP(or any other language probably)

前端 未结 4 1224
予麋鹿
予麋鹿 2021-01-21 17:50

Why does this code return -1 ?

$a = 0; 
echo ~$a;

Isn\'t not suppose to revert the bits ?

4条回答
  •  独厮守ぢ
    2021-01-21 18:26

    If you set all the bits on a two's complement integer then you get −1.

    Let me illustrate with a (very tiny) two-bit signed integer using two's complement:

    00 →  0
    01 →  1
    10 → −2
    11 → −1
    

    This is just counting up from 0, past the overflow from 1 to −2 and ending at −1. As you can see, if you clear all bits you get 0, if you set them all, you get −1 (regardless of how wide the integer is).

    (Mind you, people using BASIC knew this already, as there were no boolean operators and things work just as well with bitwise operators, except that True is −1 instead of 1.)

提交回复
热议问题