Search code examples
cbit-fields

the right way use bit field print number in binary


here is the code I found using bit field print int number in binary, but I also read that bit field only using unsigned, int for its type, so, is it legal for this code using char type ?

struct bits
{
    unsigned char ch1 : 1;//01
    unsigned char ch2 : 1;
    unsigned char ch3 : 1;
    unsigned char ch4 : 1;
    unsigned char ch5 : 1;
    unsigned char ch6 : 1;
    unsigned char ch7 : 1;
    unsigned char ch8 : 1;
};

void main()
{
    int data = -1;
    int length = 4;

    struct bits *p = &data;

    while (length--)
    {
        printf("%d%d%d%d %d%d%d%d ",
            (p + length)->ch8,
            (p + length)->ch7,
            (p + length)->ch6,
            (p + length)->ch5,
            (p + length)->ch4,
            (p + length)->ch3,
            (p + length)->ch2,
            (p + length)->ch1
            );
    }
    system("pause");
}

Solution

  • A bit-field shall have a type that is a qualified or unqualified version of _Bool, signed int, unsigned int, or some other implementation-defined type.

    Using unsigned char is allowable with some compilers as an "implementation-defined type".

    (p + length)->ch8 will go through the usual integer promotions being a parameters to a variadic function. Thus ch8 will be promoted to an int, which matches "%d".

    Code could use unsigned

    struct bits {
        unsigned ch1 : 1;//01
        unsigned ch2 : 1;
        unsigned ch3 : 1;
        unsigned ch4 : 1;
        unsigned ch5 : 1;
        unsigned ch6 : 1;
        unsigned ch7 : 1;
        unsigned ch8 : 1;
    };