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.
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.