Created
September 13, 2017 13:23
-
-
Save joisino/86d5d24acbb2ecaacbfa26fffdcec8a5 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
`x / (1<<n)` with shifts and an addition. | |
works with gcc 5.4.0 | |
http://joisino.hatenablog.com/entry/2017/09/14/210000 | |
Copyright (c) 2017 joisino | |
Released under the MIT license | |
http://opensource.org/licenses/mit-license.php | |
*/ | |
#include <stdio.h> | |
int div_pow2( int x , int n ){ | |
return ( x + (int)((unsigned int)(x >> 31) >> (32-n)) ) >> n; | |
} | |
int div_pow2_if( int x , int n ){ | |
if( x < 0 ){ | |
x += (1 << n) - 1; | |
} | |
return x >> n; | |
} | |
int main(){ | |
for( int i = -8; i <= 8; i++ ){ | |
printf( "%d %d\n", i, div_pow2( i , 2 ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment