diff --git a/src/bitutils.py b/src/bitutils.py new file mode 100644 index 0000000..8f3162f --- /dev/null +++ b/src/bitutils.py @@ -0,0 +1,39 @@ +def align_binary_to_right(value, size): + if "b" in value: + result = value.split("b")[1] + else: + result = str(value) + + return result[-size:].rjust(size, "0") + +al = align_binary_to_right + + +def shift_left(rg, fill_bit = 0): + return rg[1:] + fill_bit + +l = shift_left + + +def shift_right(rg, fill_bit = 0): + return fill_bit + rg[:-1] + +r = shift_right + + +def sum_supplementary_codes(x, y, size): + return al(bin(int("0b"+x, 2) + int("0b"+y, 2))[2:], size) + +sum = sum_supplementary_codes + + +def invert_bit(b): + if b == '0': + return '1' + elif b == '1': + return '0' + else: + print(f"binutils: detected impossible call: inv({b})") + exit(1) + +inv = invert_bit diff --git a/src/divide.py b/src/divide.py new file mode 100644 index 0000000..0db1363 --- /dev/null +++ b/src/divide.py @@ -0,0 +1,102 @@ +import bitutils as bu + +def divide(n, int_x, int_y, method): + if method == 1: + # getting binary values + x = bu.al(bin(int_x)[2:], n) + y = bu.al(bin(int_y)[2:], n) + + # getting the inverse of X + x_inv = '' + invert = False + for i in x[::-1]: + if invert: + if i == '0': + x_inv += '1' + else: + x_inv += '0' + else: + if i == '0': + x_inv += '0' + else: + x_inv += '1' + + if i == '1': + invert = True + + x_inv = x_inv[::-1] + + # writing startup register values + # registers order: RG3, RG2, RG1 + rg_table = [[['start', '1'*(n-1), y, x, '-'], ['start', '1'*(n-1), y, x_inv, '-']]] + + # iterations counter + i = 0 + + while rg_table[-1][-1][1][0] != '0': + i += 1 + rg_table.append([]) + + if rg_table[-2][-1][2][0] == '1': + rg_table[-1].append([ + i, + rg_table[-2][-1][1], # copy previous value + bu.sum(rg_table[-2][-1][2], rg_table[0][0][3], n), # RG2 := RG2 + RG1 + '-', + "RG2 := RG2 + RG1" + ]) + else: + rg_table[-1].append([ + i, + rg_table[-2][-1][1], # copy previous value + bu.sum(rg_table[-2][-1][2], rg_table[0][1][3], n), # RG2 := RG2 - RG1 + '-', + "RG2 := RG2 - RG1" + ]) + + rg_table[-1].append([ + i, + bu.l(rg_table[-1][-1][1], bu.inv(rg_table[-1][-1][2][0])), + bu.l(rg_table[-1][-1][2], '0'), + '-', + "l(RG3).RG2[n+2], l(RG2).0" + ]) + + print(rg_table[-1]) + + return rg_table, rg_table[-1][-1][1][1:] + + +if __name__ == "__main__": + # a fully functional reference + # implementation for this library + # is provided below + + raw_x = input("X: ") + raw_y = input("Y: ") + + if len(raw_x) == len(raw_y): + n = len(raw_x) + else: + n = int(input("n: ")) + + x = int("0b" + raw_x, 2) + y = int("0b" + raw_y, 2) + + method = int(input("Method: ")) + + dt, result = divide(n, x, y, method) + + from lib.prettytable import PrettyTable + pt = PrettyTable() + pt.field_names = ["Iteration", "RG3", "RG2", "RG1", "Operations"] + + for i in dt: + for j in range(len(i)): + if j+1 == len(i): + pt.add_row(i[j], divider = True) + else: + pt.add_row(i[j]) + + print(pt) + print(f"Result: {result}")