发现如果x使用C中的位运算符是除Y大 [英] Find if x is bigger than y using bitwise operator in C
问题描述
如果X> Y,则该函数将返回1,其他明智返回0。
If x > y, then this function will return 1, other wise return 0.
到目前为止,我有
int isitGreater(int x, int y) {
return (((y+((~x)+1)) >> 31) & 1);
但它不工作。
允许的老年退休金计划:法律OPS! 〜&安培; ^ | + LT;< >>
Allowed ops: Legal ops: ! ~ & ^ | + << >>
我敢肯定,我有逻辑正确,如果X - Y和我得到一个负数,这意味着Y> X,因此这个第32位是1,所以该位右移31次然后与它用1。
I'm 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".
编辑:如果x为负数,由于溢出这不起作用。如何解决,而无需使用条件语句这个溢出的问题?
edit: this does not work if x is negative, due to overflow. how can i fix this overflow problem without using conditional statements?
推荐答案
您code为我工作得很好。请提交一个有效的问题。
Your code works fine for me. Please submit a valid question.
编辑:你的算法将无法正常工作,如果x是-2147483648因为 - ( - 2147483648)(或等价,〜(-2147483648)+1)溢出
Your algorithm will not work correctly if x is -2147483648 because -(-2147483648) (or, equivalently, ~(-2147483648)+1) overflows.
这篇关于发现如果x使用C中的位运算符是除Y大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!