Multiplication

Whilst I was understanding the bits structure of binary values I did come across the page from here about how to do multiplication with binary values and thought that I might as well do it in c++ to understand abit more about the process.

The main part from that page above is

Rules of Binary Multiplication

  • 0 x 0 = 0
  • 0 x 1 = 0
  • 1 x 0 = 0
  • 1 x 1 = 1, and no carry or borrow bits

For example,

00101001 × 00000110 = 11110110 0  0  1  0  1  0  0  1 = 41(base 10)
× 0  0  0  0  0  1  1  0

= 6(base 10)
0  0  0  0  0  0  0  0
0  0  1  0  1  0  0  1
0  0  1  0  1  0  0  1

0  0  1  1  1  1  0  1  1  0 = 246(base 10)
00010111 × 00000011 = 01000101 0  0  0  1  0  1  1  1 = 23(base 10)
× 0  0  0  0  0  0  1  1

= 3(base 10)
1  1  1  1  1 carries
0  0  0  1  0  1  1  1
0  0  0  1  0  1  1  1

0  0  1  0  0  0  1  0  1 = 69(base 10)

Of which I have tried to implement in the below.

#include <iostream>
#include <bitset>
#include <limits>
 
using namespace std;
 
/* mutiplication using the binary shift operator */
int multiplication(int mul, int by)
{
    int result = 0;
    if (by > 0)
    {
        // mulitiply by (mulby) comparsion for when to add a shifted value to the result.
        // moveby, how many shifts left to shift by if there is a match.
        int mulby = 2, moveby = 1;
        while (by >= mulby)
        {
            cout << "by      = " << bitset<numeric_limits<short>::digits>(by) << endl;
            cout << "mulby = " << bitset<numeric_limits<short>::digits>(mulby) << endl;
            // bitwise add and if it is the same value as the mulby then add to the result.
            if ((by & mulby) == mulby) {
                cout << "+ result= " << bitset<numeric_limits<short>::digits>((mul << moveby)) << endl;
                result += mul << moveby;
                cout << "result   = " << bitset<numeric_limits<short>::digits>(result) << endl;
            }
            mulby = mulby << 1; // the next test if the bits values are the same.
            moveby++;           // move the result by
        }
        // and if there is a modulus of 1 from 2 then the value was odd.
        if (by % 2 == 1)
        {
            result += mul;
        }
        cout << "end result = " << bitset<numeric_limits<short>::digits>(result) << endl;
    }
    return result;
}
 
int main ()
{
  cout << multiplication(6,7) << endl;
  return 0;
}

and the output would be

by           = 000000000000111
mulby        = 000000000000010
+ result     = 000000000001100
result       = 000000000001100
by           = 000000000000111
mulby        = 000000000000100
+ result     = 000000000011000
result       = 000000000100100
end result   = 000000000101010
42

which is correct

6 * 7 = 42

Leave a Reply

Spam protection by WP Captcha-Free