【发布时间】:2013-04-10 10:51:11
【问题描述】:
我正在处理一些位操作,但在宏与内联函数中的同一行代码中遇到了奇怪的不同输出。该函数从N-th 位置返回具有L 活动位的64 位掩码:(~0<<N) - (~0<<(N+L))。有人可以告诉我输出不同的原因吗?
#include <iostream>
#include <bitset>
using namespace std;
#define ONES (~0UL)
#define MASK(from_bit, nbits) \
(ONES << (from_bit)) - (ONES << ((from_bit) + (nbits)))
inline unsigned long int mask(size_t from_bit, size_t nbits) {
return (ONES << from_bit) - (ONES << (from_bit + nbits));
}
int main(int argc, char **argv) {
cout << "using #define: " << bitset<64>(MASK(63, 3)) << endl;
cout << "using inline function: " << bitset<64>(mask(63, 3)) << endl;
return 0;
}
输出:
$ g++ -o test main.cc
main.cc: In function 'int main(int, char**)':
main.cc:15: warning: left shift count >= width of type
$ ./test
using #define: 1000000000000000000000000000000000000000000000000000000000000000
using inline function: 1000000000000000000000000000000000000000000000000000000000000100
------^
使用-O3 选项编译:
$ g++ -O3 -o test2 main2.cc
main.cc: In function 'int main(int, char**)':
main.cc:15: warning: left shift count >= width of type
$ ./test2
using #define: 1000000000000000000000000000000000000000000000000000000000000000
using inline function: 0000000000000000000000000000000000000000000000000000000000000000
------^
编译器信息:
$ g++ --version
i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)
【问题讨论】:
-
可能是因为您将(最多)64 位类型移动超过 64 位,从而导致未定义的行为。注意你的编译器警告!
-
所以溢出左移不会像我想的那样自动删除位...