Two's complement is a system for representing negative binary numbers. It can also be used to implement subtraction -- to subtract 'A" from "B" convert "A" to a negative number and add. This saves having to build hardware for adding and subtracting. As long as the system for converting from a binary number to the two's complement -- and back again -- two's complement can simplify negative number representation and subtraction as well. Converting from two's complement to decimal takes two steps: convert from two's complement to binary and then convert from binary to decimal.
Represent decimals as binary numbers by continuously dividing 2 into the number and collection the remainders. For example, to convert 13 to binary, divide 13 by 2 to get 6 and first remainder of 1. Divide 2 into 6 to get 3 and second remainder 0. Divide 2 into 3 to get 1 and third remainder of 1. Divide 2 into 1 to get 0 and reminder of 1. The remainders, in reverse order of production, are 1101 and decimal 13 = binary 1101. It is easier to recognise a binary number than it is to produce it. Starting from the right, add d X 2^p where d is the binary digit and p is the position, So 1101 = (1 X 1) + (0 x 2) + (1 X 4) + (1 X 8) = 13.
Change from binary to two's complement by reversing the bits and adding 1. So binary 7 might be 00000111 and negative 7 would be 11111001 because 00000111 reversed is 11111000 and 11111000 + 1 = 11111001. The leftmost digit is the sign bit. Positive numbers have a zero sign bit and negative numbers have a 1 sign bit. One of the nice things about two's complement is that converting from two's complement to binary is exactly the same as process as converting from binary to two's compliment. For example, to convert two's complement -7 to binary 7, reverse the digits and add 1. 11111001 reversed is 00000110 and 00000110 + 1 = 00000111.
Convert from two's complement to decimal in two steps: two's complement to binary and then from binary to decimal. For example, to convert -21 in two's complement -- 11101011 -- to decimal, first convert it into binary and then convert the binary into decimal.. Reverse 11101011 to get 00010100 and add 1 to get 00010101 which is 21 in binary. Then decode the binary using the positional notation to get (0 X 128) + (0 X 64) + (0 X 32) + (1 X 16) + (0 X 8) + (1 X 4) + (0 X 2) + (1 X 1) = 21.
There are a couple of quick validity checks: The two's complimentary number should have a one in the leftmost digit, and If the number is even the rightmost digit is zero.
Is is easy to forget to add the one after flipping the bits.
Tips and warnings
- There are a couple of quick validity checks: The two's complimentary number should have a one in the leftmost digit, and If the number is even the rightmost digit is zero.
- Is is easy to forget to add the one after flipping the bits.