gpt4 book ai didi

c - C 中的按位运算 - AnyOddBit

转载 作者:太空狗 更新时间:2023-10-29 15:59:20 30 4
gpt4 key购买 nike

我的小家庭作业的最后一个问题遇到了麻烦。如果任何奇数位设置为 1,该函数应该返回 1。这是我目前所拥有的:

int anyOddBit(int x) {
return (x & 0xaaaaaaaa) != 0;
}

这很完美,但我不允许使用那么大的常量(只允许 0 到 255,0xFF)。我也不允许使用 !=

具体来说,这是我仅限于使用的:

  Each "Expr" is an expression using ONLY the following:
1. Integer constants 0 through 255 (0xFF), inclusive. You are
not allowed to use big constants such as 0xffffffff.
2. Function arguments and local variables (no global variables).
3. Unary integer operations ! ~
4. Binary integer operations & ^ | + << >>

我不知道如何在这些限制范围内执行此操作,如果有人能指出正确的方向,我将不胜感激。提前致谢!

最佳答案

您可以在 AND 之前执行 OR:

((x>>0) | (x>>8) | (x>>16) | (x>>24)) & 0xaa

初始偏移 (x >> 0) 将被优化 - 它的存在是为了保持一致的外观。

关于c - C 中的按位运算 - AnyOddBit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10273606/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com