How does the negation ~ operator work?
Posted 08 August 2006 - 05:28 AM
The output was -3.. How??
Posted 08 August 2006 - 05:43 AM
echo $b I'm assuming...
and I'm not positive but i think it returns the value of the -($a) - 1
Posted 08 August 2006 - 06:06 AM
in the php manual its given this way
~ $a Not : Bits that are set in $a are not set, and vice versa.
What does that mean??
Posted 08 August 2006 - 08:55 AM
If $a was 3, for example, its binary would be:
However, PHP uses signed integers, so we add 128 to it to make 131 which would be represented like so:
Then we make all 1's 0's and vice versa.
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.
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.
Posted 08 August 2006 - 09:51 AM
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.
Posted 08 August 2006 - 10:18 AM
Posted 08 August 2006 - 10:23 AM
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.
Posted 08 August 2006 - 10:35 AM
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users