I’ve been trying to learn more about PHP’s bitwise operators today, and I’m having a little trouble with the ~ operator. Following online tutorials, I’ve seen that it reverses set bits in a number. For instance, if you had a byte equal to 7:
|------------------------------------|
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|------------------------------------|
| 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 |
|------------------------------------|
And reversed it using ~7:
|------------------------------------|
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
|------------------------------------|
| 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 |
|------------------------------------|
Wouldn’t that be equal to 248 and not -8?
No. The reason for this is the Two’s complement.
The very first bit of each number has got a negative value (-232 in PHP, as PHP uses 32bit (= 4 byte) numbers). When the bit is set to 1 the whole number will become negative. Therefore when using the not-operator (
~) this bit will change and the number will become negative.