Binary subtraction

 Computer subtract two numbers by using a trick called two's complement. For example, if you wanted to do A - B with A and B as binary integers, what computer actually do is A + F(B) + 1, with F() being a function that handles two's complement. Two's complement works by reversing the digits of the binary number. If A = 1101011, and B = 101, first of all, you make B the same length as A by putting 0s in the front, B = 0000101. Then, you reverse the digits, so that F(B) = 1111010. Then you add one to F(B),  B = 1111011. Then you add those two numbers together, and ignore the left-most digit. A + F(B) + 1 = 11100110. This leaves us with 1100110, which should be equal to A - B:

1101011 = 107

101 = 5

1100110 = 102 

107 - 5 = 102

number = input("Enter your binary digit: ")
array = []
for x in range(0, len(number)):
if number[x] == "1":
array.append(0)
elif number[x] == "0":
array.append(1)
number = input("Enter your second binary number to subtract the first number from: ")
second_array = []
for x in range(0, len(number)):
second_array.append(int(number[x]))
while len(array) > len(second_array):
second_array.insert(0, 0)
while len(array) < len(second_array):
array.insert(0, 1)
carry = 0
result_array = []
array.reverse()
second_array.reverse()
array[0] += 1
for x in range(0, len(array)):
if array[x] + second_array[x] + carry == 2:
result_array.append(0)
carry = 1
elif array[x] + second_array[x] + carry == 1 or array[x] + second_array[x] + carry == 0:
result_array.append(array[x] + second_array[x] + carry)
carry = 0
elif array[x] + second_array[x] + carry == 3:
result_array.append(1)
carry = 1
result_array.reverse()
print(result_array)

Comments