Why does this code return -1 ?
$a = 0; echo ~$a;
Isn't not suppose to revert the bits ?
Why does this code return -1 ?
$a = 0; echo ~$a;
Isn't not suppose to revert the bits ?
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.)