#include <stdio.h>
#define WORD 4
#define VERBOSE 1 //0
/*
* 02 DEC 2011 (CSC2304)
* Implementation of the Booth's Algorithm.
*/
void twosComplementAddition(char[], char[]);
void rightShift(char[], char);
void addition(char[], char[]);
char* twosComplementMultiplication(char M[], char Q[]) {
char C;
char *A = (char*) malloc(sizeof(char)*(2 * WORD + 1));
char processedQ[WORD+ 1];
char Q0, Q_1 = '0';
int i, j;
strcpy(A, "0000");
if (VERBOSE) {
printf("\n A | Q | M |");
printf("\n %s | %s | %s | Initial", A, Q, M);
printf("\n-------------------------------------------------------------");
}
for (i = 0, j = 1; i < WORD; i++, j++) {
Q0 = Q[WORD - 1];
if (VERBOSE) {
printf("\n %s | %s | %s | Cycle %d", A, Q, M, j);
}
if (Q0 == '0' && Q_1 == '1') {
addition(A, M);
if (VERBOSE) {
printf("\n %s | %s | %s | Addition", A, Q, M);
}
} else {
if (Q0 == '1' && Q_1 == '0') {
twosComplementAddition(A, M);
if (VERBOSE) {
printf("\n %s | %s | %s | Two's Complement", A, Q, M);
}
}
}
Q_1 = Q[WORD - 1];
rightShift(Q, A[WORD - 1]);
rightShift(A, A[0]);
if (VERBOSE) {
printf("\n %s | %s | %s | Right Shift", A, Q, M);
getch();
}
printf("\n-------------------------------------------------------------");
}
strcat(A, Q);
return A;
}
void rightShift(char reg[], char bit) {
int i;
for (i = WORD - 1; i > 0; i--) {
reg[i] = reg[i - 1];
}
reg[0] = bit;
}
void addition(char A[], char M[]) {
int i;
char c = '0';
for (i = WORD - 1; i >= 0; i--) {
if (A[i] == '0' && M[i] == '0') {
A[i] = c;
c = '0';
} else {
if ((A[i] == '1' && M[i] == '0') || (A[i] == '0' && M[i] == '1')) {
if (c == '0') {
A[i] = '1';
} else {
A[i] = '0';
}
} else {
if (A[i] == '1' && M[i] == '1') {
A[i] = c;
c = '1';
}
}
}
}
}
void twosComplementAddition(char A[], char M[]) {
int i;
char temp[WORD + 1];
for (i = 0; i < WORD; i++) {
if (M[i] == '0') {
temp[i] = '1';
} else {
temp[i] = '0';
}
}
temp[WORD] = '\0';
addition(temp, "0001");
addition(A, temp);
}
int main() {
char QQ[WORD + 1];
char M[WORD + 1];
char Q[WORD + 1];
char *result;
printf("\nBooth's Algorithm");
printf("\n*****************");
printf("\nEnter M: ");
scanf("%s", M);
printf("\nEnter Q: ");
scanf("%s", Q);
strcpy(QQ, Q);
result = twosComplementMultiplication(M, Q);
printf("\n%s * %s = %s", M, QQ, result);
printf("\n");
return 0;
}
lundi 19 octobre 2020
Booth's Algorithm - C Implementation
Inscription à :
Publier les commentaires
(
Atom
)
Aucun commentaire :
Enregistrer un commentaire