add testing division script

This commit is contained in:
dymik739 2023-04-03 23:26:59 +03:00
parent 1ab5b67c77
commit 8019753a12
2 changed files with 141 additions and 0 deletions

39
src/bitutils.py Normal file
View File

@ -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

102
src/divide.py Normal file
View File

@ -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}")