获取某一个数的2进制位数以及bitmask

举例说明:比如32对应的2进制为2b'100000,对应的bitmask为2b'11111。

实现代码:

#include <stdio.h>

typedef unsigned char uint8_t;
typedef unsigned int uint32_t;

/* 获取某一个数有多少bit */
static uint8_t _soc_get_digital_bits(uint32_t num)
{
    uint8_t count = 0;

    if (num % 2 == 0)
        num += 1;
    while(num != 0) {
        num /= 2;
        count++;
    }
    return count;
}

/* 获取bit掩码 */
static uint8_t _soc_get_digital_bitmask(uint32_t num)
{
    uint8_t bits = 0;
    uint8_t bitmask = 1;
    uint8_t i = 0;

    bits = _soc_get_digital_bits(num);
    for (i = 0; i < bits; i++)
        bitmask *= 2;
    bitmask--;

    return bitmask;
}

int main()
{
    uint32_t num = 0;
    uint8_t bits = 0;
    uint8_t bitmask = 0;

    for (num = 0; num < 33; num++)
    {
        bits = 0;
        bitmask = 0;
        bits = _soc_get_digital_bits(num);
        bitmask = _soc_get_digital_bitmask(num);
        printf("%u bits = %u, bitmask = 0x%x\n", num, bits, bitmask);
    }

    return 0;
}

编译、运行测试:

image-20211210183209057

posted @ 2021-12-10 18:34  zhengcixi  阅读(228)  评论(0编辑  收藏  举报
回到顶部