[Math] Subtracting binary using two’s complement

binarybinary operations

The question is following subtraction, where the second term has to be transformed into it's two complement.

110000 – 10101 =

twos complement of 10101 = 01011

This is the part where I'm getting confused. I notice that they are not the same length. Can I add 0s to the second term?

this (110000 + 01011) becomes this (110000 + 001011 = 111011)

I obtain the twos complement 000101

and then add a minus infront -000101

Can somebody comment on this method?

Best Answer

Two's complement is designed for an environment in which all numbers have the exact same number of bits, and you know in advance exactly how many bits that will be.

In computer languages where integers of different numbers of bits are used, the shorter integers are converted into integers of the longer type when they are in an operation with a longer integer.

If the two numbers you received were specified to be a six-bit two's complement integer and a five-bit two's complement integer, respectively, then what you did was correct. Since both the given integers start with the bit $1,$ they are both negative. So you are subtracting a negative number $y$ from another negative number $x$ of larger magnitude, and the result is a negative number of magnitude less than $x.$

But that seems to be an unlikely interpretation of the problem. Why would you have a six-bit two's complement integer and a five-bit two's complement integer as input? That is completely foreign to the way two's complement has been used in just about every application I can imagine since people stopped programming computers with patch cords.

So I think a more reasonable interpretation is that you have two positive numbers, and to do two's complement arithmetic on them you must first pad both of the numbers with zeros on the left so that they have the same number of bits and the leftmost bit of each number is zero.

A good policy is probably to make the length of each bit string a power of $2,$ since almost all two's complement integers on modern computers are defined that way (that is, $8$ bits, $16$ bits, $32$ bits, $64$ bits, or even $128$ bits may be used in practice, much more rarely something like $24$ bits and almost never an odd number of bits).

Then proceed with your two's complement and other steps of your algorithm.