【发布时间】:2018-12-08 05:27:17
【问题描述】:
我有一个std::uint32_t 并想检查是否设置了一个位。我怎样才能做到这一点,而无需像这样遍历所有位?也就是说,下面的函数可以简化吗?
static inline bool isExactlyOneBitSet(std::uint32_t bits)
{
return ((bits & 1) == bits
|| (bits & 1 << 1) == bits
|| (bits & 1 << 2) == bits
// ...
|| (bits & 1 << 31) == bits
);
}
奖励:如果返回值是找到的位或 0,那就太好了。
static inline bool isExactlyOneBitSet(std::uint32_t bits)
{
if (bits & 1) {return 1;}
else if (bits & 1 << 1) {return 1 << 1;};
//...
else if (bits & 1 << 31) {return 1 << 31;};
return 0;
}
【问题讨论】:
-
2^n 的数字只是设置了一位的数字。
-
正好一个还是至少一个?您的第一个示例至少检查一个,相当于
!= 0。 -
x && !(x & (x-1)) -
FWIW,C++20 可能会有
std::ispow2。 -
奖励答案:
return bits;.
标签: c++ bit-manipulation