To represent numbers, computers use either:
Unsigned numbers
Include only non-negative values (0 and positive numbers)
Signed numbers
Include positive and negative values
To represent negative numbers, computers use a technique called Two’s Complement.
In Two’s Complement, a negative number is created by inverting all the bits of the positive number and adding 1. The most significant bit (MSB) is used to indicate the sign. If it’s 0, the number is positive, and if it’s 1, the number is negative.
This is also why unsigned numbers can go to higher ranges. They don’t use the MSB as a sign bit, so they have one more bit available for the value.
Now, let’s look at an example of converting a number 5 to -5 using 8-bit binary.
The number 5 looks like this in 8 bits:
00000101
To get its negative, we first invert all of the bits:
~ 00000101
----------
11111010
Then, we add 1 to it:
11111010
+ 00000001
----------
11111011
This gives us -5 in Two’s Complement.
Find this post helpful? Subscribe and get notified when I post something new!