我在理解这段代码的工作方式和原因时遇到了一些困难。我在这项任务中的合作伙伴完成了这部分,我无法联系他以了解这是如何工作的以及为什么工作。我已经尝试了几种不同的方法来理解它,但我们将不胜感激任何帮助。此代码使用 2 的补码和 32 位表示。
/*
* fitsBits - return 1 if x can be represented as an
* n-bit, two's complement integer.
* 1 <= n <= 32
* Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int fitsBits(int x, int n) {
int r, c;
c = 33 + ~n;
r = !(((x << c)>>c)^x);
return r;
}
最佳答案
c = 33 + ~n;
这将计算在使用 n
个低位后剩余多少个高位。
((x << c)>>c
这会用与 x
的符号位相同的值填充高位。
!(blah ^ x)
这相当于
blah == x
关于c - 按位运算和移位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14792521/