/* | |
`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