Maximum two numbers in C using bitwise operators

Possible duplicate:
Find a maximum of two numbers without using if-else or any other comparison operator

isGreater:

if x > y then return 1, else return 0 

Example:

  • isGreater (4,5) = 0
  • isGreater (5,4) = 1

Legal Operators ! ~ & ^ | + << >> ! ~ & ^ | + << >>

isGreater is a feature.

I tried:

 int isGreater(int x, int y) { return (y+(~x+1)) >> 31 & 1; } 

but it doesn’t work ..: ((Let me know what else can I do?

+2
source share
2 answers

given x, y

try x + -y if <0, then y is greater, if> 0, then x is greater.

-y = binary complement to y:

 -y = (~(y-1)) <==> -y = (~y)+1 

From what I see, you are doing a binary addition with (~ y +1)), which is the same thing.

Then bitdrive β†’ 31 to get MSB and equal to 1.
Be sure to set the brackets, operator priority!

  (y+-x) >> (31 & 1); != ((y+-x) >> 31) & 1; 
0
source

Too simple - since you have + in the list of legal operators, you can trivially synthesize - (as others have noted) and thus subtract and extract the sign. Its much more interesting if you omit + (since this is not a bitwise operator anyway) and answer the question only with bitwise ops ( & | ^ ~ ) and shifts.

Of course, you can synthesize + from bitwise ops and shifts, but it's actually simpler.

0
source

All Articles