I am writing a program that implements Booth's Algorithm to multiply ints. I am only allowed to use bit-level operators, logical operators, and bit shifts. I am allowed one loop for the program, and a function that will add two ints. I am having trouble understanding what is going wrong with my program. When I am using bitwise operators to mask half of the long long, I am getting incorrect values. Any advice on what I am doing wrong there? Maybe I am not understanding how to mask properly. It also may have to do with type casting; I am really unsure. Thanks in advance for any help!
Here is by code:
#include <stdio.h>
int Add (int x, int y);
long long Booth (int x, int y);
int main() {
int hex1, hex2;
long long product;
printf("\nEnter Multiplicand & Multiplier in hex: ");
scanf(" %x %x", &hex1, &hex2);
product = Booth(hex1, hex2);
printf("Multiplicand = 0x%08X \tAs signed = %+d\n", hex1, hex1);
printf("Multiplier = 0x%08X \tAs signed = %+d\n", hex2, hex2);
printf("Product = 0x%16X \tAs signed = %+d\n", product, product);
}
int Add (int x, int y) {
return x + y;
}
long long Booth (int multiplicand, int multiplier) {
int i;
long long product;
long long productLH;
long long productRH;
int productLHI;
int productRHI;
int cOut;
int negMultiplicand;
negMultiplicand = Add (~multiplicand, 1);
product = (long long) Add (0, multiplier);
for (i = 0; i < 32; i++) {
if (((product & 1) == 1) && (cOut == 0)) {
//Mask left half and right half of product
productLH = (product & 0xFFFFFFFF00000000);
productRH = (product & 0x00000000FFFFFFFF);
//Bit shift product so all values are in lower 32 bits
productLH = (productLH >> 32);
//Convert left halves and right halves to ints
productLHI = (int) (productLH & 0x00000000FFFFFFFF);
productRHI = (int) productRH & (0x00000000FFFFFFFF);
productLHI = Add(productLHI, negMultiplicand);
//Put halves back together
product = (long long) Add(productLHI, 0);
product = ((product << 32) & 0xFFFFFFFFFFFFFFFF);
product = (long long) Add((int)product, productRHI);
}
else if (((product & 1) == 0) && (cOut == 1)) {
//Mask left half and right half of product
productLH = (product & 0xFFFFFFFF00000000);
productRH = (product & 0x00000000FFFFFFFF);
//Bit shift product so all values are in lower 32 bits
productLH = (productLH >> 32);
//Convert left halves and right halves to ints
productLHI = (int) (productLH & 0x00000000FFFFFFFF);
productRHI = (int) productRH & (0x00000000FFFFFFFF);
productLHI = Add(productLHI, multiplicand);
//Put halves back together
product = (long long) Add(productLHI, 0);
product = ((product << 32) & 0xFFFFFFFFFFFFFFFF);
product = (long long) Add((int)product, productRHI);
}
cOut = (product & 1);
product = product >> 1;
}
return product;
}