Skip to content

Instantly share code, notes, and snippets.

@joisino
Created September 13, 2017 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joisino/86d5d24acbb2ecaacbfa26fffdcec8a5 to your computer and use it in GitHub Desktop.
Save joisino/86d5d24acbb2ecaacbfa26fffdcec8a5 to your computer and use it in GitHub Desktop.
/*
`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