How does the bit field work with character types?

struct stats { char top : 1; char bottom : 1; char side : 2; } MyStat; 

I saw this format with integers, but how does the above char bit field work and what does it represent?

Thanks.

+5
source share
3 answers

Char bit fields work just like int, only the base type is 8-bit, not 32-bit. Thus, you will get statistics of the structure, which has a size of 1 byte and 3 members of variables, occupying a total of 4 bits.

+5
source

Battle fields must be declared with the 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 with the signature - plain int may be considered unsigned for the bit field.

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

According to C99 6.7.2.1/9,

The bit field is interpreted as an integer with or without a signature, consisting of the specified number of bits. If a value of 0 or 1 is stored in a bit field with a non-zero width of type _Bool, the value of the bit field must be compared with the stored value.

and footnote:

As indicated in clause 6.7.2 above, if the actual specifier of type int or the name typedef is defined as int , then it is determined by the implementation whether the bit field is signed or unsigned.

+5
source

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

 char int 

This is not supported by the standard (typical use is unsigned int), but this is a good attempt :)

re: your request, this is an attempt by the executor to use less memory for his bit fields (char as opposed to unsigned int)

In addition, from Atmel we get:

in the C standard, only unsigned (int) and int are acceptable datatypes for a bit field member. Some compilers allow unsigned char ........

+2
source

Source: https://habr.com/ru/post/949527/


All Articles