【发布时间】:2016-03-22 06:29:01
【问题描述】:
x 的来源已更新。这是一项任务,我被要求填写该功能。分配的要求是我不能更改参数类型或进行任何类型转换。所以我有这个问题。
我想使用 c 实现位计数。代码如下:
int bitCount(int x) {
int mask1 = 0x55555555;
int mask2 = 0x33333333;
int mask3 = 0x0f0f0f0f;
int mask4 = 0x00ff00ff;
int mask5 = 0x0000ffff;
//x = 0xffffffff;
if (x != 0xffffffff) {
exit(0);
}
printf("%x\n", x);
x = (x & mask1) + ((x >> 1) & mask1);
printf("%x\n", x);
x = (x & mask2) + ((x >> 2) & mask2);
printf("%x\n", x);
x = (x & mask3) + ((x >> 4) & mask3);
printf("%x\n", x);
x = (x & mask4) + ((x >> 8) & mask4);
printf("%x\n", x);
x = (x & mask5) + ((x >> 16) & mask5);
printf("%x\n", x);
return x;
}
当x = -1(或十六进制的0xffffffff)时,答案应该是0x20。但实际上输出是:
ffffffff
aaaaaaaa
24444444
6080808
e0010
1e
如果我取消注释该行
代码中"x = 0xffffffff",输出变为:
ffffffff
aaaaaaaa
44444444
8080808
100010
20
操作系统是 Mac OS X。gcc 版本是:
gcc --version
配置:
--prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.0.2 (clang-700.1.81)
Target: x86_64-apple-darwin14.5.0
Thread model: posix
为什么?
【问题讨论】:
-
x究竟从何而来? -
另外,版本字符串清楚地表明这实际上不是 gcc,而是 clang。我假设 OSX 别名是 gcc。
-
@PaulR 当然没有最小、完整和可验证的例子,因为这是 UB :D
-
@AnttiHaapala:好吧,我会满足于最小和完整。 ;-)