判断一个整数的二进制表示中,第i位是否为1
check.cpp内容如下:
#include <iostream>
using namespace std;
// check if the i-th bit is set or not in the binary form of n.
bool check(int n, int i)
{
if (n & (1 << i))
return true;
return false;
}
int main(int argc, char **argv)
{
const int kRange = 20;
for (int i = 0; i < kRange; ++i)
if (check(i, 3))
cout << "The 3rd bit is set in the binary form of " << i << endl;
return 0;
}
运行结果如下图: