zoukankan      html  css  js  c++  java
  • 获取某一个数的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

  • 相关阅读:
    Django(一)
    web 框架
    图片
    day16
    day 15
    day14 HTML CSS
    day12
    day11
    python IO多路复用,初识多线程
    python socket
  • 原文地址:https://www.cnblogs.com/mrlayfolk/p/15673366.html
Copyright © 2011-2022 走看看