小编jjj*_*jjj的帖子

将位移位到掩码中给出的位置的快速方法

我正在寻找一种快速迭代掩码中所有可能的位分配的方法.

例:

mask = 0b10011

result = {0b00000,0b00001,0b00010,0b00011,0b10000,0b10001,0b10010,0b10011}

我需要迭代所有这些.

目前我使用与此类似的代码,效果很好:

int count = popCount(mask);
uint64_t number = 0;
for(uint64_t number = 0; number < (1 << count); ++number)
{
    uint64_t result = shiftBits(mask, number, count);
    //work with result
    //only some light operations
}
// shiftBits(0b10011, 0b101, 3) == 0b10001
// shiftBits(0b10011, 0b111, 3) == 0b10011
// shiftBits(0b10011, 0b000, 3) == 0b00000
uint64_t shiftBits(uint64_t mask, uint64_t number, int count) {
    uint64_t result = 0;
    for(int i = 0; i < count; …
Run Code Online (Sandbox Code Playgroud)

c++ bit-manipulation

5
推荐指数
1
解决办法
150
查看次数

标签 统计

bit-manipulation ×1

c++ ×1