简体   繁体   English

联合的位域使用

[英]Bit Field Usage with Union

I want to create a simple package with bit fields by using union.我想通过使用联合创建一个带有位字段的简单包。 But when I tried to set "bit1" to 1, then all off my bit fields became "1".但是当我尝试将“bit1”设置为 1 时,我的所有位域都变为“1”。 How can I solve this problem, I want to do that bit field part by using union not by using struct.我该如何解决这个问题,我想通过使用联合而不是使用结构来完成位域部分。

So here my struct;所以这里是我的结构;

    struct {
    union{
        uint8_t bit1 :1 ;
        uint8_t bit2 :1 ;
        uint8_t bit3 :1 ;
        uint8_t bit4 :1 ;
        uint8_t bit5 :1 ;
        uint8_t bit6 :1 ;
        uint8_t bit7 :1 ;
        uint8_t bit8 :1 ;


    }bits;
    uint8_t trial;


    }myStruct_t;

int main(int argc, char *argv[]) {
        myStruct_t.bits.bit1 = 1;
        myStruct_t.bits.bit2 = 0;
        printf("%x",myStruct_t.bits);
        printf("%x",myStruct_t.bits.bit1);
        printf("%x",myStruct_t.bits.bit2);

    return 0;
}

And the output is: 000.输出为:000。

Swap your union with your struct .用你的struct交换你的union

Ie I believe you want a union of a struct and an int, not a struct of a union and an int.即我相信你想要一个结构和一个 int 的联合,而不是一个联合和一个 int 的结构。 (I kept the now misleading name myStruct_t , which probably should be myUnion_t now.) (我保留了现在具有误导性的名称myStruct_t ,现在可能应该是myUnion_t 。)

#include <stdio.h>
#include <stdint.h>

union
{
    struct
    {
        uint8_t bit1 :1 ;
        uint8_t bit2 :1 ;
        uint8_t bit3 :1 ;
        uint8_t bit4 :1 ;
        uint8_t bit5 :1 ;
        uint8_t bit6 :1 ;
        uint8_t bit7 :1 ;
        uint8_t bit8 :1 ;
    }bits;
    uint8_t trial;
}myStruct_t;

int main(int argc, char *argv[])
{
    myStruct_t.trial=0; // use the encompassing union member for init
    myStruct_t.bits.bit1 = 1; // now use the bitwise view to set bits
    myStruct_t.bits.bit2 = 0;
    printf("%x",myStruct_t.trial);
    printf("%x",myStruct_t.bits.bit1);
    printf("%x",myStruct_t.bits.bit2);

    return 0;
}

The output I get is 110, you might see 12810. Apart from the absent newlines, which would have helped, it means:我得到的输出是 110,你可能会看到 12810。除了缺少换行符之外,这会有所帮助,这意味着:

  • the encompassing 8bit-view has a value of 1, at least with the endianess of my environment - you might see 128包含的 8 位视图的值为 1,至少在我的环境的字节序中 - 您可能会看到 128
  • the bit 1 has a value of 1位 1 的值为 1
  • the bit 2 has a value of 0位 2 的值为 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM