Created
February 28, 2017 21:24
-
-
Save dpyro/86857dfeacfc02002946bb761447e72f to your computer and use it in GitHub Desktop.
returns the maximum of two ints without a comparison operator
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
#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