Booth algorithm


























class booth {

 int q[];

 int m[];

 int mn[];

 int bit = 0;

 int a[] = {0, 0, 0, 0};


 booth(int multiplicand[], int multiplier[]) {

  this.q = multiplier;

  this.m = multiplicand;

  mn = new int[m.length];


  for (int i = m.length - 1; i > -1; i--) {

   mn[i] = (m[i] + 1) % 2;


  }

  findMinusM();

  doStuff();

 }

 void findMinusM() {

  int carry = 1;

  if (mn[mn.length - 1] + 1 == 1) {

   carry = 0;

  };

  mn[mn.length - 1] = (mn[mn.length - 1] + 1) % 2;

  int total = 0;

  for (int i = mn.length - 2; i > -1; i--) {

   if (carry == 0) {

    return;

   }

   total = carry + mn[i];

   if (total == 1) {

    mn[i] = 1;

    carry = 0;

   } else {

    mn[i] = 0;

    carry = 1;

   }


  }


 }


 void doStuff() {

  int x;

  for (int i = 0; i < m.length; i++) {

   x = check(q[q.length - 1], bit);

   switch (x) {

   case 00:

    doArs();

    break;

   case 11:

    doArs();

    break;

   case 10:

    update(mn);

    doArs();

    break;

   case 01:

    update(m);

    doArs();

    break;

   }

  }

 }

 int check(int LD, int NB) {


  if (LD == 0 && NB == 0) {


   return 00;

  }

  if (LD == 0 && NB == 1) {

   return 01;

  }

  if (LD == 1 && NB == 0) {


   return 10;

  }

  if (LD == 1 && NB == 1) {

   return 11;

  }


  return -1;


 }

 void update(int n2[]) {

  int total = 0;

  int carry = 0;

  for (int i = n2.length - 1; i > -1; i--) {

   total = a[i] + n2[i] + carry;

   if (total > 1) {

    carry = 1;

   } else {

    carry = 0;

   }

   a[i] = total % 2;


  }

 }


 void doArs() {

  int bitByA = a[a.length - 1];

  int bitByQ = q[q.length - 1];

  bit = bitByQ;

  for (int i = a.length - 1; i > -1; i--) {

   if (i == 0) {

    a[i] = bitByQ;

    q[i] = bitByA;

    return;

   } else {

    a[i] = a[i - 1];

    q[i] = q[i - 1];

   }

  }

 }

 void printResult() {

  for (int i = 0; i < a.length; i++) {

   System.out.print(a[i]);

  }


  for (int i = 0; i < a.length; i++) {

   System.out.print(q[i]);

  }

 }

}

class work {

 public static void main(String args[]) {

  int multiplicand[] = {0, 1, 1, 0};

  int multiplier[] = {0, 0, 1, 0};

  booth obj = new booth(multiplicand, multiplier);

  obj.printResult();

 }

}

Comments