def multiply(x, y): """ Input: positive integers x and y, in binary output: their product """ xlen = len(x) ylen = len(y) print "xlen:ylen :: ", xlen, ylen n = max(xlen, ylen) if n == 1: return str(int(x) * int(y)) m = n/2 xL, xR = x[:m], x[m:] yL, yR = y[:m], y[m:] P1 = multiply(xL, yL) P2 = multiply(xR, yR) P3 = multiply(binsum(xL, xR), binsum(yL, yR)) # print "P1, P2, P3: ", P1, P2, P3 P4 = binsum(P1, P2) print "P1, P2, P3, P4: ", P1, P2, P3, P4 print "n, m: ", n, m a = P1 + ("0" * n) b = bin_subtract(P3, P4) b = b + ("0" * m) result = binsum(a, b) result = binsum(result, P2) # print ("maxlen is: ", maxlen) return result
def two_complement(k): klen = len(k) result = [] for i in range(klen): if int(k[i]) == 0: result.append('1') else: result.append('0') one = "1" result = ''.join(result) result = binsum(result, one) return result
def bin_subtract(x, y): """ assumes x and y are binary strings """ xlen = len(x) ylen = len(y) diff = abs(xlen - ylen) z = "0" * diff # print "Z: ", z if xlen > ylen: y = z + y elif xlen < ylen: x = z + x # print "X: ", x # print "Y: ", y yc = two_complement(y) # print "Y 2 complement: ", yc result = binsum(x, yc) result = result[1:] result = result.lstrip("0") # print "result: ", result return result