-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbooths_algorithm.py
153 lines (98 loc) · 2.42 KB
/
booths_algorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# Python3 code to implement booth's algorithm
# function to perform adding in the accumulator
def add(ac, x, qrn):
c = 0
for i in range(qrn):
# updating accumulator with A = A + BR
ac[i] = ac[i] + x[i] + c;
if (ac[i] > 1):
ac[i] = ac[i] % 2
c = 1
else:
c = 0
# function to find the number's complement
def complement(a, n):
x = [0] * 8
x[0] = 1
for i in range(n):
a[i] = (a[i] + 1) % 2
add(a, x, n)
# function to perform right shift
def rightShift(ac, qr, qn, qrn):
temp = ac[0]
qn = qr[0]
print("\t\trightShift\t", end = "");
for i in range(qrn - 1):
ac[i] = ac[i + 1]
qr[i] = qr[i + 1]
qr[qrn - 1] = temp
# function to display operations
def display(ac, qr, qrn):
# accumulator content
for i in range(qrn - 1, -1, -1):
print(ac[i], end = '')
print("\t", end = '')
# multiplier content
for i in range(qrn - 1, -1, -1):
print(qr[i], end = "")
# Function to implement booth's algo
def boothAlgorithm(br, qr, mt, qrn, sc):
qn = 0
ac = [0] * 10
temp = 0
print("qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc")
print("\t\t\tinitial\t\t", end = "")
display(ac, qr, qrn)
print("\t\t", sc, sep = "")
while (sc != 0):
print(qr[0], "\t", qn, sep = "", end = "")
# SECOND CONDITION
if ((qn + qr[0]) == 1):
if (temp == 0):
# subtract BR from accumulator
add(ac, mt, qrn)
print("\t\tA = A - BR\t", end = "")
for i in range(qrn - 1, -1, -1):
print(ac[i], end = "")
temp = 1
# THIRD CONDITION
elif (temp == 1):
# add BR to accumulator
add(ac, br, qrn)
print("\t\tA = A + BR\t", end = "")
for i in range(qrn - 1, -1, -1):
print(ac[i], end = "")
temp = 0
print("\n\t", end = "")
rightShift(ac, qr, qn, qrn)
# FIRST CONDITION
elif (qn - qr[0] == 0):
rightShift(ac, qr, qn, qrn)
display(ac, qr, qrn)
print("\t", end = "")
# decrement counter
sc -= 1
print("\t", sc, sep = "")
if __name__=="__main__":
mt = [0] * 10
# Number of multiplicand bit
brn = 4
# multiplicand
br = [ 0, 1, 1, 0 ]
# copy multiplier to temp array mt[]
for i in range(brn - 1, -1, -1):
mt[i] = br[i]
br.reverse()
complement(mt, brn)
# No. of multiplier bit
qrn = 4
# sequence counter
sc = qrn
# multiplier
qr = [ 1, 0, 1, 0 ]
qr.reverse()
boothAlgorithm(br, qr, mt, qrn, sc)
print("\nResult = ", end = "")
for i in range(qrn - 1, -1, -1):
print(qr[i], end = "")
print()