位域用法

Devin'sBlog / 2023-07-13 / 原文

目录

    如果有字段定义为int类型的话,那么符号位的判断需要特别注意。
    例如:下面的 B::f2 字段是有符号类型,其符号位是f2的最高位,可以表示的范围是-64~63

    #include <iostream>
    
    struct B {
        unsigned int f1:1;
        int f2:7;
    };
    
    int main()
    {
        B b1 = {0, 10};
        B b2 = {0, 127};
    
        std::cout << std::boolalpha << (b1.f2 >= 0) << std::endl; // true
        std::cout << std::boolalpha << (b2.f2 >= 0) << std::endl; // false
    }