Search code examples
c++cstructunsignedbit-fields

values changed in bitfields in structure


Can anyone explain the output , how the value is stored and calculated?

#include<stdio.h>
struct bitfield
{
    unsigned f1:1;
    unsigned f2:2;
    unsigned   :3;
    unsigned f4:4;
    unsigned f5:5;
    unsigned f6:6;
    unsigned f7:1;
    unsigned f8:8;
} bf;

main()
{
    bf.f1 = 1;
    bf.f2 = 0x3;
    bf.f4 = 0xff;
    bf.f5 = -4;
    bf.f6 = 0377;
    printf("%d %d %d %d %d %d", bf.f1, bf.f2, bf.f4, bf.f5, bf.f6, bf.f8);
}

Output: 1 3 15 28 63 0


Solution

  • unsigned fx:n; // Only use the least significant n bits.
    
                   //                        Binary    Decimal
    bf.f1 = 1;     // 1    == [0000 0001]:1   == 1      == 1
    bf.f2 = 0x3;   // 0x3  == [0000 0011]:2   == 11     == 3
    bf.f4 = 0xff;  // 0xff == [1111 1111]:4   == 1111   == 15
    bf.f5 = -4;    // -4   == [0xfffffffc]:5  == 11100  == 28
    bf.f6 = 0377;  // 0377 == [1111 1111]:6   == 111111 == 63