C++ – Bitwise Less than or Equal to

bit-manipulationclogic

There seems to be some kind of misconception that this is for a contest.
I'm trying to work through an assignment and I've been stuck on this for an hour now.

 /*
     * isLessOrEqual - if x <= y  then return 1, else return 0 
     *   Example: isLessOrEqual(4,5) = 1.
     *   Legal ops: ! ~ & ^ | + << >>
     *   Max ops: 24
     *   Rating: 3
     */
    int isLessOrEqual(int x, int y)
    {
        int greater = (x + (~y + 1))>>31 & 1;
        return !(greater)|(!(x^y));

    }

I'm only able to use bitwise operators, as instructed in the comments.
I cannot figure out how to solve x <= y;

My thought process is that I can set x as its two's complement (~x +1) and add it with Y. If it is negative, X is greater than Y. Therefore, by negating that I can get the opposite effect.

Similarly, I know that !(x^y) is equivalent to x==y.
However,
doing !(greater)|(!(x^y)) does not return the proper value.

Where am I messing up? I feel like I'm missing a small bit of logic.

Best Answer

Those functions don't fully work because of the overflow, so that's how I solved the problem. Eh...

int isLessOrEqual(int x, int y) {
int diff_sgn = !(x>>31)^!(y>>31);      //is 1 when signs are different
int a = diff_sgn & (x>>31);            //diff signs and x is neg, gives 1
int b = !diff_sgn & !((y+(~x+1))>>31); //same signs and difference is pos or = 0, gives 1
int f = a | b;
return f;
}