c - Why does this greater than function work? -
i working on homework assignment supposed make function called isgreater(x,y) returns if x larger y, can use bitwise operators along + , !. have solved problem, using rule if x , y have different signs, x >= 0 , y < 0 or if x , y have same sign if y-x negative.
however, when looking around how other people solved it, noticed following method works correctly whatever reason.
y = ~y; return !(((x&y) + ((x^y) >> 1)) >> 31);
i cannot life of me understand why works, figure has first bit in x isn't set in y or something?
note: apparently valid solution if x , y ints, not unsigned int.
31 means interested in sign. if ((x&y) + ((x^y) >> 1)) > 0 x > ~y.
x & ~y produce number msb first bit x has set bit , y has 0. x^~y produce number unset bits represent bits x , y differ. if shift right 1 need sum become positive. happen if first nonzero bit of of x&y (meaning first bit x set , x , y different) meets set bit in ((x^y) >> 1) (meaning first bit set in 1 not set in other).
, if highest bit set in x not set in y, highest bit set in 1 not set in other - means x bigger y.
example:
(shft x^~y >> 1, res shft + x&~y) x: 000110 y: 001010 ~y: 110101 x&~y:000100 x^~y:110011 shft:111001 res: 111101 -> negative x: 000110 y: 000010 ~y: 111101 x&~y:000100 x^~y:111011 shft:111101 res: 000001 -> positive
this why does't work unsigned btw (no sign there).
Comments
Post a Comment