Reputation: 744
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?
Upvotes: 1
Views: 247
Reputation: 3394
It's the Two' complement that the left-most bit indicates the symbol, 0 for positive and 1 for negative. The Two' complement is computed by invert the bits and add 1. In this case, it's 1111000(except the symbol bit), then subtract 1(1110111) and invert it(0001000, negative), so it's -8. In C, the scope of integer with sign is from -2^15-1 to 2^15.
Upvotes: 0
Reputation: 32731
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.
Upvotes: 1