-1

我正在处理一些位操作,并在宏与内联函数中的同一行代码中遇到奇怪的不同输出。该函数从-th 位置返回具有L活动位的 64 位掩码: 。有人可以告诉我输出不同的原因吗?N(~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)
4

2 回答 2

0

您的编译器警告说明了这一点。

您的移位量 ( from_bit + nbits) 大于您使用的类型的大小。

宏和函数的区别在于,前者没有类型检查。

于 2013-04-10T11:04:35.067 回答
0

您不应忽略编译器警告。它告诉你有问题。

在法律上,您只能移动比整数类型中的位数更少的位置。

这有效:

#include <iostream>
#include <bitset>
using namespace std;

#define ONES (~0ULL)

#define MASK(from_bit, nbits) \
  (ONES << (from_bit)) - (ONES << (from_bit) << (nbits))

inline unsigned long long mask(unsigned from_bit, unsigned 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;
}

输出(ideone):

using #define:         1000000000000000000000000000000000000000000000000000000000000000
using inline function: 1000000000000000000000000000000000000000000000000000000000000000
于 2013-04-10T11:04:44.970 回答