I'm working on an exercise that asks to get the remainder of diving two integers using bitwise operators but not to use the % operator. I've read back through my books but I am still having an issue doing this. Can anybody give an example of how this could be done.
For as long as the dividend is larger then the divisor, subtract the divisor from the dividend, this is the new dividend. When the divisor is finally larger, this is the remainder.
Appreciate the reply, Any chance you could knock out a line or tow of code to show the example. I'm still grasping the terminology which makes understanding it harder.
agreed to Intrexa's comment. Also you can checkout from the "always so trusted" wikipedia about topic "modulo operation"... THE answer is writed there ;P
Dividend / divisor = quotient. If I 'knock out a line or tow of code' that would be completing the entire assignment for you, which I don't want to do.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int number;
cout << "Enter a number: ";
cin >> number;
cout << "Thank you. The remainder after dividing your number by 8 is "
<< number - ((number >> 3) << 3);
cout << endl;
return 0;
}
Ok so i got home and it seems to work. One thing i don't quite get while i managed to make this work by backtracking it. Does this principle of shifting bits like this always work to reveal the remainder. Is it some principle of mathematics i seem to have completely missed. The annoying this is my book which asked me to do this assignment nowhere did it touch on this it just explained how the bitwise shift operators worked. But did not explain that you can get a remainder by doing that.
Everytime you shift to the right, it is the same as integer division by 2, with the remainder discarded. When you shift back to the left, it is the same as multiplying by 2, but you do not reclaim that lost remainder. The difference between those 2 numbers is the remainder.