我正在看一些应该是微不足道的代码 - 但我的数学在这里惨遭失败.
这是一个条件,使用以下内容检查数字是否为2的幂:
if((num != 1) && (num & (num - 1))) { /* make num pow of 2 */ }
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何在num和num-1之间使用按位AND来确定数字是2的幂?
我有一个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
);
}
Run Code Online (Sandbox Code Playgroud)
奖励:如果返回值是找到的一位或为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 …Run Code Online (Sandbox Code Playgroud)