Two's Complement is the way most computers store negative numbers.
To find the negative of a number, write it in binary, then flip all the bits and add 1.
Example (in 8 bits):
. 19 = 0001 0011
flips all bits 1110 1100
add one + 0000 0001
. __________
. -19 = 1110 1101
Example 2:
. 1 = 0000 0001
flip all bits 1111 1110
add one + 0000 0001
. __________
. -1 = 1111 1111
Some less useful information follows.
Why is two's complement notation so common? Well, it has this really neat property:
In eight bits...
10 = 00001010 ==> -10 = 11110110
8 = 00001000 ==> -8 = 11111000
And then
10 00001010
+ 8 +00001000
---- ---------
18 00010010 ==> -18 = 11101110
-10 11110110
+ -8 +11111000
---- ---------
-18 11101110 ==> 18 = 00010010
As you can see, under at least addition and multiplication the computer doesn't have to care at all whether a number is positive or negative. This makes computer hardware much easier (and therefore cheaper) to produce: you only need one set of ADD instructions, not one for unsigned (all positive) integers and another one for signed (some positive, some negative) numbers. Imagine having to test whether a number is negative or positive before being able to decide how to add it to another number!
There is, however, a small disadvantage to two's complement notation. Since zero is considered a positive number (as its leading bit is, unsurprisingly, 0) there is one more negative number than positive numbers. See here:
In eight bits...
+-+-+-+-+-+-+-+---- (These are the values of the bits in 8 bit two's complement, by the way)
| | | | | | | |
v v v v v v v v
-
1
2 6 3 1
8 4 2 6 8 4 2 1
0 1 1 1 1 1 1 1 = 64 + 32 + 16 + 8 + 4 + 2 + 1 = 127, the most positive number.
1 0 0 0 0 0 0 0 = -128, the most negative number.
Suppose we try to negate -128 to make +128 in eight bits. Let's try it.
Invert the bits and add one:
01111111
+ 00000001
10000000 <-- oops! -(-128) is -128.
Actually, it's 010000000, but we don't have enough bits to show that.
Note that LSL uses 32-bit integers and not 8-bit as in these examples.
BooleanLogic