简体   繁体   English

如果仅使用按位和逻辑运算符将任何偶数位设置为 1,则返回 1

[英]Return 1 if any even bit is set to 1 using only bitwise and logical operators

I am currently stuck on a function that I need to write that checks if any even numbered bits are set to 1. For example, evenBit(0x1) returns 1, evenBit(0x2) returns 0, and evenBit(0xFFFFFFFF) returns 1. Currently my evenBit() function looks like this:我目前被困在 function 上,我需要编写它来检查是否有任何偶数位设置为 1。例如, evenBit(0x1)返回 1, evenBit(0x2)返回 0, evenBit(0xFFFFFFFF)返回 1。目前我的evenBit() function 看起来像这样:

unsigned int evenBit(unsigned int x) {
    unsigned int evenMask = 0x55555555;
    return x & evenMask;
}

But these aren't returning the results that I was expecting but I'm not entirely sure how to approach this.但是这些并没有返回我期望的结果,但我不完全确定如何解决这个问题。 I want to isolate the even bits with the mask, which I've done, but I'm not sure what to do with the result after so that it will become 1, without using if statements or any other operators that aren't for bit manipulation, like.=.我想用我已经完成的掩码隔离偶数位,但我不确定如何处理结果以使其变为 1,而不使用 if 语句或任何其他不适合的运算符位操作,例如.=。

Your posted code is already correct in the sense that the function evenBit will return a nonzero value (true) if any of the bits are set, and zero (false) if not.您发布的代码已经是正确的,如果设置了任何位,则 function evenBit将返回非零值(真),如果没有设置,则返回零(假)。

If you want to restrict the return values to 0 and 1 , then you can change the line如果要将返回值限制为01 ,则可以更改该行

return x & evenMask;

to:至:

return !!( x & evenMask );

This will apply the logical-NOT operator !这将应用逻辑非运算符! twice.两次。

The logical-NOT operator will evaluate to 0 if its operand is nonzero, and to 1 if its operand is zero.如果操作数非零,则逻辑非运算符的计算结果为0 ,如果其操作数为零,则计算结果为1 Therefore, this operation gives you the exact opposite of the result that you want.因此,此操作为您提供与您想要的结果完全相反的结果。 Applying the logical-NOT operator a second time will give you the desired result.再次应用逻辑非运算符将为您提供所需的结果。

Normally, a programmer would write通常,程序员会写

return ( x & evenMask ) != 0;

or或者

return ( x & evenMask ) ? 1 : 0;

to achieve the exact same result, however this would violate the restrictions stated in your question of only using bitwise and logical operators.为了达到完全相同的结果,但这将违反您在仅使用按位和逻辑运算符的问题中所述的限制。

Using only bitwise operators (and assignments),仅使用位运算符(和赋值),

x |= x >> 16;
x |= x >>  8;
x |= x >>  4;
x |= x >>  2;
return x & 1;

Like the OP, I assumed x is a 32-bit unsigned int, though that isn't guaranteed.与 OP 一样,我假设x是 32 位无符号整数,但不能保证。 It could be smaller or larger.它可能更小或更大。

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

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