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

前端 未结 4 1196
予麋鹿
予麋鹿 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:16

    That zero is actually being represented by 32 zero bits, as PHP integer types are 32-bit signed integers, and not single bits:

    0000 0000 0000 0000 0000 0000 0000 0000
    

    So bitwise NOT flips all of them, resulting in the two's complement of -1 (with the leftmost one representing the sign):

    1111 1111 1111 1111 1111 1111 1111 1111
    

提交回复
热议问题