C/C++共用体内嵌位结构体

共用体内嵌位结构体可以对整型某些位进行操作,下面以C++的32位无符号整型为例说明:

#include <iostream>
#include <bitset>

int main() {
    typedef union {//共用体
        struct {//位结构体
            unsigned int c6:9;//最后的数字为位宽
            unsigned int c5:7;
            unsigned int c4:7;
            unsigned int c3:5;
            unsigned int c2:3;
            unsigned int c1:1;//注意大小端
        } bit;
        unsigned int num;
    } UInt32Union;
    unsigned int n = (1U << 31);//2^31
    std::cout << "n:\t" << n << std::endl;
    std::cout << "n(b):\t" << bitset<32>(n) << std::endl;
    UInt32Union anUnion = *((UInt32Union *) &n);
    anUnion.bit = {6, 5, 4, 3, 2, 0};//与定义顺序一致,高位在尾处
    std::cout << "u:\t" << anUnion.num << std::endl;
    std::cout << "u(b):\t" << bitset<32>(anUnion.num) << std::endl;
    return 0;
}

运行结果:

n:      2147483648
n(b):   10000000000000000000000000000000
u:      562301446
u(b):   00100001100001000000101000000110

在多次循环中可以减少频繁的位运算来对某些位进行操作。

发表评论

电子邮件地址不会被公开。 必填项已用*标注