I am working on homework where we need to create a function called isGreater (x, y) that returns if x is greater than y, but we can only use bitwise operators along with + and !. I already solved the problem using the rule, if x and y have different signs, then x> = 0 and y <0, or if x and y have the same sign, then only if yx is negative.
However, when I watched other people solve this, I noticed the following method, which works for some reason.
y = ~y; return !(((x&y) + ((x^y) >> 1)) >> 31);
I canβt let my life understand why this works, I suppose this has to do with the first bit in x, which is not set to y or something like that?
Note. Apparently this is only a valid solution if x and y are ints and not unsigned int.
source share