Skip to content

Instantly share code, notes, and snippets.

@dpyro
Created February 28, 2017 21:24
Show Gist options
  • Save dpyro/86857dfeacfc02002946bb761447e72f to your computer and use it in GitHub Desktop.
Save dpyro/86857dfeacfc02002946bb761447e72f to your computer and use it in GitHub Desktop.
returns the maximum of two ints without a comparison operator
#define INT_MIN 1 << (sizeof(int)*8 - 1)
int max(int a, int b) {
unsigned int ua = (unsigned int) a - INT_MIN;
unsigned int ub = (unsigned int) b - INT_MIN;
int k = ((ub-ua) >> (sizeof(int)*8 - 1)) & (0x1);
return k*a + (1-k)*b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment