How can I access a specific group of bits from a variable?

前端 未结 4 1019
梦谈多话
梦谈多话 2021-02-06 06:58

I have a variable with \"x\" number of bits. How can I extract a specific group of bits and then work on them in C?

4条回答
  •  庸人自扰
    2021-02-06 07:35

    You can use bitfields in a union:

    typedef union {
    unsigned char value;
    struct { unsigned b0:1,b1:1,b2:1,b3:1,b4:1,b5:1,b6:1,b7:1; } b;
    struct { unsigned b0:2,b1:2,b2:2,b3:2; } b2;
    struct { unsigned b0:4,b1:4; } b4;
    } CharBits;
    
    
    CharBits b={0},a={0};
    printf("\n%d",b.value);
    b.b.b0=1; printf("\n%d",b.value);
    b.b.b1=1; printf("\n%d",b.value);
    printf("\n%d",a.value);
    a.b4.b1=15; printf("\n%d",a.value); /* <- set the highest 4-bit-group with one statement */
    

提交回复
热议问题