Difference of binary numbers
Hello.
I made a bitwise addition of binary numbers, but how to make the difference between two binary numbers, namely, when the reduced is less than the subtracted, for example, 10-111 (in binary), when at the end there is no one to borrow from. I need the answer to be negative. I don't understand how this can be arranged.
2 answers
Write the binary representation of the number in the additional code. Then you can replace the subtraction A - B
with the addition A + (-B)
. Changing the sign of a number in the additional code is performed by inverting its bits and adding 1. After performing the subtraction operation, do not forget to correctly interpret the result (taking into account the additional code). In your case, the subtraction will look like this:
- Write
-111
in the additional code. To do this, invert the original number (000
) and add 1 (001
). In the highest digit, we write 1 (this means that the number is negative), we get1001
. - Adding
10 + 1001 = 1011
. - Remember that
1011
is an entry of a number in the additional code. The highest digit is responsible for the sign: 1 is-
, 0 is+
. If the highest digit is0
, then it is discarded, and the remaining number is interpreted as positive. If the highest digit is1
, then the number is negative, and it must be inverted as we did this is with the original number. That is,1011 -> 011 -> 100 -> 101
. We get10 - 111 = -101
(2 - 7 = -5
) in the direct code or0010 + 1001 = 1011
in the additional code.
If you do not need additional code, but just a binary number with a sign, then just check two numbers and if the first is less than the second (your situation), then swap them, subtract, just add a minus to the result.