For
unsigned numbers you may simply right shift the numbers, until their leading bit (MSB) is different. e.g.
(I'm pretty sure there are more efficient ways, have a look, if you can at
"Hacker's Delight"[
^] book).
#include <stdlib.h>
#include <stdio.h>
int compare(unsigned int a, unsigned int b);
int main()
{
unsigned int a, b;
int i;
for (i = 1; i<20; i++)
{
a =rand();
b= rand();
switch (compare(a,b))
{
case -1:
printf("%u is smaller than %u\n", a, b);
break;
case 0:
printf("%u is equal to %u\n", a, b);
break;
case 1:
printf("%u is greater than %u\n", a, b);
break;
}
}
return 0;
}
int compare(unsigned int a, unsigned int b)
{
unsigned int fb = 1 << (sizeof(a)*8-1);
while ( !( (a ^ b) & fb))
{
a <<= 1;
b <<= 1;
if (!a && !b) return 0;
}
if ( a & fb)
return 1;
else
return -1;
}