Есть такой код сравнения двух чисел ( > ):
int isGt(int a, int b)
{
int diff = a ^ b;
diff |= diff >> 1;
diff |= diff >> 2;
diff |= diff >> 4;
diff |= diff >> 8;
diff |= diff >> 16;
//1+ on GT, 0 otherwise.
diff &= ~(diff >> 1) | 0x80000000;
diff &= (a ^ 0x80000000) & (b ^ 0x7fffffff);
//flatten back to range of 0 or 1.
diff |= diff >> 1;
diff |= diff >> 2;
diff |= diff >> 4;
diff |= diff >> 8;
diff |= diff >> 16;
diff &= 1;
return diff;
}
Не могу распарсить как оно работает. Пробую на 4хбитных числах:
int isGt(int a, int b)
{
# a = 1100
# b = 1110
int diff = a ^ b;
# diff = 0010
diff |= diff >> 1;
# diff = 0010 | 1 = 0011
diff |= diff >> 2;
# diff = 0011 | 0 = 0011
diff |= diff >> 4;
diff |= diff >> 8;
diff |= diff >> 16;
# diff = 0011
//1+ on GT, 0 otherwise.
diff &= ~(diff >> 1) | 0x80000000;
# diff = ~(110) | 1000 = 1001 & 0011 = 1
diff &= (a ^ 0x80000000) & (b ^ 0x7fffffff);
# diff = 1100 ^ 1000 = 0100
1110 ^ 0111 = 1001
0100 & 1001 = 0
1 & 0 = 0 // <-- Сломалось, ибо должен быть 1
//flatten back to range of 0 or 1.
diff |= diff >> 1;
diff |= diff >> 2;
diff |= diff >> 4;
diff |= diff >> 8;
diff |= diff >> 16;
diff &= 1;
return diff;
}
Как оно работает?