Jump to content

How does the negation ~ operator work?


praveenhotha

Recommended Posts

Do you know binary? I think this is what it means:
If $a was 3, for example, its binary would be:
00000011
However, PHP uses signed integers, so we add 128 to it to make 131 which would be represented like so:
10000011
Then we make all 1's 0's and vice versa.
01111100
This is 124, if we subtract 128 from this we get -4, so we know that ~13=-4

Now we can try it for 13. 13+128=141.
10001101
Reversed to:
01110010
Which is 114. 114-128=-14.

Therefore we can conclude that what corbin said is half correct. ~$a==-($a)-1 is true if you're starthing with a positive number, but it's ~$a==-($a)+1 if you're starting with a negative.
Well not quite.

A signed 8 bit number can represent values from -128 through to +127. This is because 127 is 01111111. Adding one more makes it 10000000, which now represents -128, because it is taken to mean 128 - 256. The 8th bit is the sign bit, if it is 0 then the number is positive, if it is 1 then it's negative and represents the number - 256. So if $a is 2, 00000010 in binary, and you take the NOT of that number (~ means logical NOT, or XOR with 11111111) you get 11111101 which is 253. 253 - 256 is -3.
Because an unsigned 8 bit number can store up to 255. To put it another way, 2 to the power 8 is 256.

It will work for any size integer. If we're using 16 bit numbers, then a signed 16 bit number goes from -32768 to +32767, and this time we are subtracting 65536 which is 2 to the power 16.

Basically if you understand binary you will get it, if you don't you won't.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.