Compare two integers with bitwise operation

71 Views Asked by At

I saw a bunch of codes which can do simple arithmetic operations in constant-time.

But there is a code makes me curious.

Here is a code written in C.

int ct_lt_u32(uint32_t x, uint32_t y){
    return (x^((x^y)|((x-y)^y)))>>31;
}

This function returns 1 if x<y, 0 otherwise.

However, I cannot understand why this function works. Can anyone help me to understand this function? There are only XOR, OR, shift and subtraction.

0

There are 0 best solutions below