Created
April 14, 2014 14:56
-
-
Save jmagnuson/10655552 to your computer and use it in GitHub Desktop.
Finds maximum/minimum value between two signed integers without the use of conditionals
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
#include <stdlib.h> | |
#include <stdio.h> | |
#define INT_SHIFT ( (sizeof(int) - 1) * 4 ) | |
int max_val( int a, int b ) | |
{ | |
int *val_ptrs[2] = {&a, &b}; | |
int difference_bit = ( ( *val_ptrs[0] - *val_ptrs[1] ) & | |
(const int)( 8 << INT_SHIFT ) | |
) >> (const int)( 3 + INT_SHIFT ); | |
return *val_ptrs[difference_bit]; | |
} | |
int min_val( int a, int b ) | |
{ | |
int *val_ptrs[2] = {&a, &b}; | |
int difference_bit = ( ( *val_ptrs[1] - *val_ptrs[0] ) & | |
(const int)( 8 << INT_SHIFT ) | |
) >> (const int)( 3 + INT_SHIFT ); | |
return *val_ptrs[difference_bit]; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int a=0, b=0; | |
a = atoi( argv[1] ); | |
b = atoi( argv[2] ); | |
printf("%d\n", max_val( a, b ) ); | |
printf("%d\n", min_val( a, b ) ); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment