相关疑难解决方法(0)

如何计算32位整数中的设置位数?

代表数字7的8位看起来像这样:

00000111
Run Code Online (Sandbox Code Playgroud)

设置三位.

什么算法来确定32位整数中的设置位数?

algorithm binary bit-manipulation hammingweight iec10967

838
推荐指数
31
解决办法
52万
查看次数

这个按位运算如何检查2的幂?

我正在看一些应该是微不足道的代码 - 但我的数学在这里惨遭失败.

这是一个条件,使用以下内容检查数字是否为2的幂:

if((num != 1) && (num & (num - 1))) { /* make num pow of 2 */ }
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何在num和num-1之间使用按位AND来确定数字是2的幂?

c math bit-manipulation

39
推荐指数
4
解决办法
7万
查看次数

如何检查int中是否只设置了一位?

我有一个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)

c++ bit-manipulation

0
推荐指数
2
解决办法
1506
查看次数

标签 统计

bit-manipulation ×3

algorithm ×1

binary ×1

c ×1

c++ ×1

hammingweight ×1

iec10967 ×1

math ×1