Why is it that the bitwise NOT operator (~
in most languages) converts the following values like so:
-2 -> 1
-1 -> 0
This is because the bit-wise operator literally inverts each bit in the word. It is NOT strictly an arithmetic operation, it is a logic operation.
-2 == %1110, ~-2 == ~%1110 = %0001 == 1 -1 == %1111, ~-1 == ~%1111 = %0000 == 0
and so on.
To go from -2 to 2, and 1 to -1 you need to use the arithmetic negation operation.
See two's complement for the representation of negative integers in many languages. As you can see, -2 is represented by 1111110
; if you invert all those bits you get 0000001
, i.e. a value of 1.
This is due to how negative numbers are represented as bits. For this most commonly Two's Complements are used.
-2 happens to be 1111110 in this notation, which negated is 1
The numbers in computer systems are stored as 2 complementary. If number is positive then 2 complement of positive number is same.But for the negative number it is different.
1.-2 -> 1 Here -2 will be stored in computer as 1110(i.e. 2's complement of -2).Now ~ of 1110 is 0001.As 0001 is positive number it will be stored in computer as 0001(i.e.1)
2.-1 -> 0 Here -1 will be stored in computer as 1111(i.e. 2's complement of -1).Now ~ of 1111 is 0000.As 0000 is positive number it will be stored in computer as 0000(i.e.0)
0 -> -1 Here 0 will be stored in computer as 0000(i.e. 2's complement of 0).Now ~ of 0000 is 1111.As 1111 is negative number it will be stored in computer as 0001(i.e.-1)(since MSB is set for 1111 the number will be negative)
1 -> -2 Here 1 will be stored in computer as 0001(i.e. 2's complement of 1).Now ~ of 0001 is 1110.As 1110 is negative number it will be stored in computer as 0010(i.e.-2)(since MSB is set for 1110 the number will be negative)
It helps if you look at it in binary.
First of all, as you know, negative numbers are expressed as (highest possible unsigned number plus 1 minus value). So -1 in a 16-bit integer, which has the highest unsigned value of 65535, would be 65536-1=65535, i.e. 0xffff in hex, or 1111 1111 1111 1111
in binary.
So:
1 in binary = 0000 0000 0000 0001
NOT on all bits would result in 1111 1111 1111 1110
. That, in decimal, is 65534. And 65536 minus 65534 is 2, so this is -2.
Most (all?) modern architectures use two's complement to represent signed integers. The bitwise NOT is thus the complement of the integer minus one.