/* mutiplication using the binary shift operator */ int multiplication(int mul, int by) { int result = 0; if (by > 0) { // mulitiply by (mulby) comparison 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; }
Comments
Leave a comment