Up to this point, we have only dealt with how to encode positive integers in binary. To encode negative integer values you must use two’s complement binary encoding. You are used to using eight bits to store any of 256 possible values ranging from 0 to 255. In two’s complement, you still use eight bits to store any of 256 possible values, but this time they range from -128 to 127. Two’s complement is an encoding method that is, at first, a little confusing. However, once you understand the process it is actually very simple. There are two methods. Both methods involve working with a value and flipping the sign (e.g. if you want the two’s complement binary for -56, write out the binary for 56 and then perform the calculations required to flip the sign, giving you -56). Note that the same method can be also used to convert a negative value into a positive one. In our examples below, we will convert 116 into -116 using two’s complement encoding.
Method 1
This method is simple. Firstly, write out the binary value:
Note that the Most Significant Bit (MSB) is used to represent -128, not 128. You can use this to check your answers if you’re unsure in the exam.
Next, flip every bit:
Finally, using binary addition[1], add 1 to the value:
You now have the two’s complement binary encoding for -116.
Method 2
Start from the Least Significant Bit (LSB), moving left until you find a 1:
Ignore the first ‘1’:
Flip every bit that follows:
You now have your answer.
A few important notes
Firstly, two’s complement is used to encode positive values as well as negative values. If you’re asked to give the two’s complement for a positive value, it’s exactly the same as it would be if it were encoded as a standard binary integer. Read the question carefully.
Two’s complement values don’t have the same range as their positive binary integer equivalents. You can’t store 128 in an 8-bit two’s complement value. You’ll need at least nine bits to store it. Be careful.
All two’s complement values where the MSB is ‘1’, are negative. Always. The opposite is also true.
Finally, if you ever need to pad bits (i.e. add more bits to the left of a binary value to make it a certain length, such as a byte), just as you’d use zeroes to pad a positive value (e.g. 0011 -> 00000011), you must use ones to pad a negative value (e.g. 1011 -> 11111011).
[1] Put simply, binary addition is very similar to denary addition, including ‘carrying the one’. The only difference is that digits can only range from 0-1. Binary addition depends on some very simple rules: 0 + 0 = 0; 0 + 1 = 1; 1 + 0 = 1; 1 + 1 = 0 carry 1; 1 + 1 with a carried 1 = 1 carry 1. You can find plenty of online tutorials for this if you wish to understand it further.