Skip to content

Instantly share code, notes, and snippets.

@jeborgesm
Created June 9, 2015 00:30
Show Gist options
  • Save jeborgesm/160c0d08a66379c47da4 to your computer and use it in GitHub Desktop.
Save jeborgesm/160c0d08a66379c47da4 to your computer and use it in GitHub Desktop.
C++ Integer division with remainder bitwise
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int value = 0;
int const divisor = 8;
int remainder = 0;
cout << "\nEnter an integr and I'll divide it by 8 and give you the remainder!"
<< endl;
cin >> value;
//remainder = (int)(value / divisor);
//remainder = remainder & 7;
remainder = value;
while (remainder >= divisor)
{
remainder -= divisor;
}
cout << "\nThe remainder is " << remainder << " isn't that awesome?!"
<< endl;
//Compute modulus division by 1 << s without a division operator
unsigned int n = 0; // numerator
const unsigned int s = 0;
const unsigned int d = 8U << s; // So d will be one of: 1, 2, 4, 8, 16, 32, ...
cout << "Now Let's try it moving bits around"
<< endl;
cin >> n;
unsigned int m = 0; // m will be n % d
m = n & (d - 1);
cout << "The remainder is " << m << " isn't that awesome?!"
<< endl;
//Most programmers learn this trick early, but it was included for the sake of completeness.
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment