Can anybody tell the internal procedure of the below code
<? $temp = 0; echo ~$temp; ?>
//instead of 1 it displays -1
echo ~$temp;
^bitwise not operator
Assuming 32-bit, Bitwise inverse of 0000
is FFFF
(All 1
's) which is -1
, in signed int's case.
Another way to look at it: What ~
did is to give you the (One's complement)
In order to get the negative of a number, you take the 2's complement, which is just the
1's complement + 1
So,
(1's complement of 0) + 1 = 0 //negative 0 is 0
hence, 1's complement of 0 = -1
Bitwise-not (~):
This inverts each bit of its operand. If the operand is a floating point value, it is truncated to an integer prior to the calculation. If the operand is between 0 and 4294967295 (0xffffffff), it will be treated as an unsigned 32-bit value. Otherwise, it is treated as a signed 64-bit value
Its because you're actually dealing with a full 32-bit unsigned integer with NOT. What that means is you're not simply inverting 0001 but inverting 00000000000000000000000000000001
which becomes 11111111111111111111111111111110
essentially this is the number + 1 and negated. so 1 becomes -(num+1) which is -1 or 1111111111111111111111111111110 in binary (unsigned)
for example:- $temp=1; echo~$temp; print -2 //-(n++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With