如何从确定的位置检查一组位是否为0?

时间:2016-08-23 09:50:40

标签: c bit-manipulation bitmapdata

我正在写一个位图物理内存管理器,我希望实现一个函数来检查n位是否从特定位开始是空闲的。 现在我使用这个函数来检查单个位是否空闲,我调用它n次以查看n位是否空闲,但我认为这样做效率不高:

inline static bool physical_memory_map_test(uint32_t bit)
{
    return physical_memory.blocks[bit/32] & (1 << bit % 32);
}

所以我想实现这样的东西:(&#34;&#34;包含伪代码):

static bool physical_memory_map_test(uint32_t starting_bit, uint32_t count)
{
    int excess = (starting_bit%32 + count) -32;
    if(excess < 0)
        return (physical_memory.blocks[bit/32] & "-excess number of 1s" << bit % 32)) && (physical_memory.blocks[bit/32] & "count + excess number of 1s" << bit % 32));

    return physical_memory.blocks[bit/32] & ("count number of ones, if count is 3, this should be 111" << bit % 32); 
}

或者更好的方法来检查所有位是否为0(返回true)或者其中至少有一位是1(返回false) 我怎么能这样做?

1 个答案:

答案 0 :(得分:5)

由于您正在检查一系列uint32_t个单词,因此最终会出现循环。你的任务是使它循环32位而不是循环1位。

您需要检查两端的部分32位字:

Bit groups

为此,您需要构建一个掩码,其k低位设置为1,高(32-k)设置为0。你可以这样做:

uint32_t mask_K = ~(~0U << k);

使用

if (block & mask_K)

测试较低的k位;

if (block & ~mask_K)

测试高k位。