简体   繁体   English

为什么这比功能大?

[英]Why does this greater than function work?

I am working on a homework assignment where we are supposed to make a function called isGreater(x,y) which returns if x is larger than y, but we can only use bitwise operators along with + and !. 我正在做一个家庭作业,我们应该创建一个名为isGreater(x,y)的函数,如果x大于y则返回,但我们只能使用按位运算符和+和!。 I have already solved the problem, using the rule if x and y have different signs, then x >= 0 and y < 0 or if x and y have the same sign then only if yx is negative. 我已经解决了问题,如果x和y有不同的符号,则使用规则,然后x> = 0且y <0或者如果x和y具有相同的符号,则仅当yx为负时。

However, when i was looking around how other people solved it, i noticed the following method which works correctly for whatever reason. 然而,当我环顾四周其他人如何解决它时,我注意到以下方法无论出于何种原因都能正常工作。

y = ~y;   
return !(((x&y) + ((x^y) >> 1)) >> 31); 

I cannot for the life of me understand why this works, i figure this has something to do with the first bit in x that isn't set in y or something? 我不能为我的生活理解为什么这有效,我认为这与x中的第一位没有设置在y或其他东西有关?

Note: Apparently this is only a valid solution if x and y are ints, not unsigned int. 注意:显然,如果x和y是整数,而不是unsigned int,这只是一个有效的解决方案。

31 means we are only interested in the sign. 31表示我们只对标志感兴趣。 If ((x&y) + ((x^y) >> 1)) > 0 then x > ~y. 如果((x&y)+((x ^ y)>> 1))> 0则x> ~y。
x & ~y will produce a number where the MSB will be the first bit where x has a set bit and y has a 0. x^~y will produce a number where the unset bits will represent the bits where x and y differ. x&〜y将产生一个数字,其中MSB将是第一位,其中x具有设置位并且y具有0.x ^ ~y将产生一个数字,其中未设置位将表示x和y不同的位。 If we shift it right by one we need for their sum to become positive. 如果我们将它正确地移动一个,我们需要他们的总和变得积极。 Which will happen only if the first nonzero bit of of x&y (meaning the first bit where x is set and x and y are different) meets with a set bit in ((x^y) >> 1) (meaning the first bit that is set in one but not set in the other). 只有当x和y的第一个非零位(意味着设置x并且x和y不同的第一个位)与((x ^ y)>> 1)中的设置位相遇时才会发生这种情况(意味着第一位设置为一个但未设置为另一个)。
And if the highest bit is set in x but not set in y, is also the highest bit set in one but not set in the other - this means x is bigger than y. 如果最高位在x中设置但未在y中设置,则也是在一个中设置的最高位但在另一个中未设置 - 这意味着x大于y。

Example: 例:

(shft is x^~y >> 1, res is shft + x&~y)

x:   000110
y:   001010
~y:  110101
x&~y:000100
x^~y:110011
shft:111001
res: 111101 -> negative

x:   000110
y:   000010
~y:  111101
x&~y:000100
x^~y:111011
shft:111101
res: 000001 -> positive

This is why it does't work for unsigned BTW (no sign there). 这就是为什么它不适用于未签名的BTW(没有迹象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM