How does a bit field work with character types?

前端 未结 3 476
栀梦
栀梦 2020-12-11 19:21
   struct stats
   {
       char top         : 1; 
       char bottom      : 1;
       char side        : 2;
   } MyStat;  

I have seen this format

相关标签:
3条回答
  • 2020-12-11 19:34

    Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.

    0 讨论(0)
  • 2020-12-11 19:41

    it just defines the size of the variable that you will use.

    char
    int
    

    This is not supported by the standard (typical use is unsigned int), but it's a nice attempt :)

    re: your query, it's an attempt by the implementer to use less memory for their bitfields (char as opposed to unsigned int)

    Additionally, from Atmel, we get:

    in the C Standard, only “unsigned (int)” and “int” are acceptable datatypes for a bitfield member. Some compilers allow “unsigned char” ........

    0 讨论(0)
  • 2020-12-11 19:51

    Bitfields should be declared with type signed int, unsigned int, or bool from <stdbool.h>. Other types may or may not be legal (depending on the platform), but be careful about the signedness — plain int may be taken to be unsigned for a bitfield.

    That said, it may be a hint to the compiler that the alignment of the struct should be 1 and not sizeof(int). And the compiler is allowed to accept char and assign it such meaning.

    According to C99 6.7.2.1/9,

    A bit-field is interpreted as a signed or unsigned integer type consisting of the specified number of bits. If the value 0 or 1 is stored into a nonzero-width bit-field of type _Bool, the value of the bit-field shall compare equal to the value stored.

    and a footnote:

    As specified in 6.7.2 above, if the actual type specifier used is int or a typedef-name defined as int, then it is implementation-defined whether the bit-field is signed or unsigned.

    0 讨论(0)
提交回复
热议问题