# Thread: Using bitwise operator to see if x>y

1. ## Using bitwise operator to see if x>y

If x > y, then this function will return 1, other wise return 0.
so far i have
int isitGreater(int x, int y) {

return (((y+((~x)+1)) >> 31) & 1);
but it's not working.
Im sure i have the logic right, if X - Y and I get a negative number, that means y > x , so therefore the 32nd bit is a 1, so i shift that bit to the right 31 times and then "and" it with "1".
why isnt it working?

2. It's working fine

3. Originally Posted by sana.iitkgp
It's working fine

not if X is negative and causes a overflow

4. Obviously it'll fail if x is INT_MIN, but otherwise it seems okay.
Give some specific values for which it fails.

5. if X is -4 and y is 5

this will cause an overflow in my code but i dont know how to handle this overflow error without using if/while statements

6. or: error i have is: (-2147483648[0x80000000],2147483647[0x7fffffff]) fail

7. What exactly is the purpose and the constraints of this exercise?

8. To only use : Legal ops: ! ~ & ^ | + << >>

and no conditional statments, working with bitwise operators

9. For x=-4 and y=5 it is working fine for me.

10. Originally Posted by Lina_inverse
if X is -4 and y is 5

this will cause an overflow in my code but i dont know how to handle this overflow error without using if/while statements
Take x is -4, y is 5
Where's the overflow?
It seems to give the correct answer 0.

Your second example (-2147483648) is INT_MIN, which I pointed out won't work since you can't take the 2's complement of it (i.e., there's no corresponding positive number).

11. how should I fix my second error? and what do you mean by INT_min?

12. INT_MIN is the minimum integer that can be represented by the int data type.
It depends on the number of bits for int and whether it is signed/unsigned.

13. Originally Posted by sana.iitkgp
It depends on the number of bits for int and whether it is signed/unsigned.
int is always signed.

14. >> how should I fix my second error?
Use a larger integer type to find the result.

>> and what do you mean by INT_min?
The type int is the default integer type, usually but not necessarily the same size as a WORD on the machine architecture. INT_MIN has to stand for the smallest value that can be represented by this type, and must be at least (-2)^16 IIRC.

15. Hey,

I have to admit that I have a soft-spot for bitwise operations.

I have a few suggestions for you
Code:
`((~x)+1))`
This is the 2's complement that is a lot easier to write like this:
Code:
`(-x)`
And instead of saying "31", you can include <limits.h> and use this instead
Code:
`sizeof(int) * CHAR_BIT - 1`
This leaves your subroutine looking like this:
Code:
```int isitGreater(int x, int y)
{
return (((y-x) >> (sizeof(int) * CHAR_BIT - 1)) & 1);
}```