Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Created April 30, 2012 08:05
Show Gist options
  • Save AndrewBarfield/2556422 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/2556422 to your computer and use it in GitHub Desktop.
C#: Bit Twiddling: Determine the minimum or maximum of two integers
using System;
namespace BitTwiddling {
class Program {
// Compute the minimum of two integers without branching
static int Min(int x, int y) {
return y + ( ( x - y ) & ( ( x - y ) >> ( sizeof( int ) * 8 - 1 ) ) );
}
// Compute the maximum of two integers without branching
static int Max(int x, int y) {
return x - ( ( x - y ) & ( ( x - y ) >> ( sizeof( int ) * 8 - 1 ) ) );
}
static int GetRandomInt() {
// Generate a 'random' integer
int rndInt = new Random().Next( 10, 50 );
// Random integer generation is based on the system clock.
// Sleep so the next 'random' integer is unique.
System.Threading.Thread.Sleep( rndInt );
return rndInt;
}
static void Main(string[] args) {
// Generate 10 pairs of 'random' integers and compare them
// using Min() and Max()
for ( int i = 0 ; i < 10 ; i++ ) {
int x = GetRandomInt();
int y = GetRandomInt();
Console.WriteLine( "Min({0},{1}) = {2}", x, y, Min( x, y ) );
Console.WriteLine( "Max({0},{1}) = {2}\n", x, y, Max( x, y ) );
}
// Allow user to read the Console
Console.Read();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment