First of all, all data in a computer is stored in binary (either 0 or 1), including the representation of positive and negative numbers, which can only be expressed using 0 or 1. Therefore, if the highest bit of a binary number is 0
, it represents a positive number
, and if it is 1
, it represents a negative number
.
Using the Sign-Magnitude Calculation#
Let's assume we have the values 2 and -2 as shown below:
- The sign-magnitude representation of
+2
is0000_0010
. - The sign-magnitude representation of
-2
is1000_0010
.
Now, let's perform the calculation 2 + (-2):
0000_0010
+1000_0010
=1000_0100
(in decimal,-4
)
Clearly, the above calculation result is not what we expected.
Using the Ones' Complement Calculation#
To address the issue mentioned above, we introduce the concept of ones' complement
.
Ones' complement: The ones' complement of a
positive number
is the same as itssign-magnitude representation
, while the ones' complement of anegative number
is obtained by inverting all the bits except the sign bit.
- The ones' complement of
+2
is0000_0010
. - The ones' complement of
-2
is1111_1101
.
Now, let's perform the calculation 2 + (-2):
0000_0010
+1111_1101
=1111_1111
The above result1111_1111
is in ones' complement form. Converting it to sign-magnitude representation gives1000_0000
, which is equivalent to-0
in decimal.
From the above, it can be observed that using ones' complement
introduces the issue of +0
and -0
.
Using the Two's Complement Calculation#
To address the issue mentioned above, we introduce the concept of two's complement
.
Two's complement: The two's complement of a
positive number
is the same as itssign-magnitude representation
, while the two's complement of anegative number
is obtained by taking the ones' complement and adding1
to the least significant bit.
- The two's complement of
+2
is0000_0010
. - The two's complement of
-2
is1111_1110
.
Now, let's perform the calculation 2 + (-2):
0000_0010
+1111_1110
=0000_0000
The above result is exactly what we expected, so computers use the two's complement for calculations.