what is the difference between ~ and -
ie difference between ~10 and -10
Explanation needed
The bitwise operator ~ (pronounced as tilde) is a complement operator.
~ is a 1’s complement operator.
7 ==> 00000000000000000000000000000111
~7==>111111111111111111111111111111111111111111000 which is equal to -8.
How -8 will be stored in computer memory ?
Negative numbers are stored in the form of 2’s complement.
2’s complement can be calculated by adding +1 to 1’s complement of a number.
8 ==> (00000000000000000000000000001000)
1’s complement of 8 ==> (11111111111111111111111111110111)
Add +1 11111111111111111111111111110111 + 1 ==>11111111111111111111111111111000 (-8)
So ~7 binary representation is equals to -8 binary representation.
So ~7 is -8.
So ~10 is just 1s complement of 10 in binary form. (Means change 0s to 1s and 1s to 0)
Whereas -10 will be stored in memory by taking 1s complement of 10 and then adding 1 to it.