Skip to content

Instantly share code, notes, and snippets.

@sriramster
Created December 4, 2020 17:18
Show Gist options
  • Save sriramster/ed1291629d499a8c03bdddfd9c7dce8a to your computer and use it in GitHub Desktop.
Save sriramster/ed1291629d499a8c03bdddfd9c7dce8a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#define CHAR_BIT 8
int min(int x, int y)
{
return y ^ ((x ^ y) & -(x < y)); // min(x, y)
}
int max(int x, int y)
{
return x ^ ((x ^ y) & -(x < y)); // max(x, y)
}
int min_dirty(int x, int y)
{
return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // min(x, y)
}
int max_dirty(int x, int y)
{
return x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // max(x, y)
}
int main(int argc, char * argv[])
{
printf("min test: %d\n", min(2, 3));
printf("max test: %d\n", max(2, 3));
printf("min test: %d\n", min(-2, -3));
printf("max test: %d\n", max(-2, -3));
printf("min test: %d\n", min_dirty(2, 3));
printf("max test: %d\n", max_dirty(2, 3));
printf("min test: %d\n", min_dirty(-2, -3));
printf("max test: %d\n", max_dirty(-2, -3));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment