Created
June 9, 2015 00:30
-
-
Save jeborgesm/160c0d08a66379c47da4 to your computer and use it in GitHub Desktop.
C++ Integer division with remainder bitwise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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