isGreater按位Ç操控 - 最大的两个数 [英] isGreater bitwise C manipulation - greatest of two numbers
问题描述
位操作,我必须找到最大的两个数字。这些是规则是相同的:
Bitwise manipulation and I have to find the greatest of two numbers. These are the rules for the same:
/*
* isGreater - if x > y then return 1, else return 0
* Example: isGreater(4,5) = 0, isGreater(5,4) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
*/
这是code,我这个写的:
This is the code I've written for this:
int isGreater(int x, int y) {
/* to find greater, subtract y from x using 2's complement method.
* then find 2's complement of the answer and shift right by 31 to give MSB
* which is 1 if x>y and 0 if x<y */
int ydash=(~y)+0x01;
int diff=x+ydash;
int a=(~diff)+0x01;
int b=a>>31;
int c=b&0x01;
return c;
}
对于我得到这个错误:
For which I get this error:
错误:测试isGreater(-2147483648 [0x80000000的] 2147483647 [0x7FFFFFFF的])失败...
...给出了1 [为0x1。应该是0为0x0]
ERROR: Test isGreater(-2147483648[0x80000000],2147483647[0x7fffffff]) failed... ...Gives 1[0x1]. Should be 0[0x0]
我允许使用unsigned int类型,但没有其他数据类型。我不知道怎么说,虽然愿意帮助。我该如何解决这个问题?
I'm allowed to use unsigned int, but no other data types. I'm not sure how that'd help though. How do I get around this?
推荐答案
通过X = -2147483648和y = 2147483647则x - Y = -4,294,967,295这范围之外 INT
,因此结果不能被重新$ p $的变量psented和你有不确定的行为。
With x = -2147483648 and y = 2147483647 then x - y = -4,294,967,295 which is outside the range of int
, hence the result cannot be represented in the variable and you got undefined behavior.
要克服这一点,你需要使用一个类型不是INT宽。当你在只允许使用unsigned int类型,你必须自己实现大INT操作,如果你想使用一个更大的类型。你也可以用另一种方式像单独检查溢出条件
To get over this you need to use a type wider than int. As you are only allowed to use unsigned int, you'll have to implement big int operations yourself if you want to use a bigger type. You can also use another way like checking the overflow condition separately
if ((x ^ y) & 0x80000000) // x and y have different sign
{
return (y >> 31) & 1; // return 1 if y is negative
}
else // x and y have the same sign, overflow never occurs
{
unsigned int xu = x, yu = y;
unsigned int xmu = ~xu + 1U;
unsigned int diffu = yu + xmu;
return diffu >> 31;
}
如果您不允许使用条件,您可以使用一个复用器来混流值
If you aren't allowed to use conditionals you can use a muxer to mux the values
unsigned int r1 = (y >> 31) & 1U; // 1st case
unsigned int xu = x, yu = y;
unsigned int xmu = ~xu + 1U;
unsigned int diffu = yu + xmu;
unsigned int r2 = diffu >> 31; // 2nd case
unsigned int s = ((x ^ y) >> 31) & 1U; // s = 1 if x and y have different sign, 0 otherwise
unsigned int mask = 0xFFFFFFFFU + s;
return (r1 & ~mask) | (r2 & mask);
这篇关于isGreater按位Ç操控 - 最大的两个数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!