C language Bit Field Description

#include <stdio.h>
/* 定义简单的结构 */
struct
{
    unsigned int widthValidated;
    unsigned int heightValidated;
} status1;

/* 定义位域结构 */
struct
{
    unsigned int widthValidated : 12;
    unsigned int heightValidated : 21;

} status2;

int main()
{
    printf("Memory size occupied by status1 : %d\n", sizeof(status1));
    printf("Memory size occupied by status2 : %d\n", sizeof(status2));

    return 0;
}

The result is:

Memory size occupied by status1 : 12
Memory size occupied by status2 : 8

Bit segment, C language allows bit field specifies the length of its members share a memory structure, such a member in bits called "bit block" or "bit field" (bit field). Bit segment using fewer bits can be used to store data. From Baidu Encyclopedia

Here are some rules:
a predetermined, can not exceed the width of the field types of data lengths which it is attached. More simply, member variables are typed, this type limits the maximum length of the member variables: the latter figure should not exceed this length.

如果将heightValidated的位数改为了33,就会超出int的最大位数4X8=32,
程序会报错:
	位域的大小无效
/* 定义位域结构 */
struct
{
    unsigned int widthValidated : 12;
    unsigned int heightValidated : 33;

} status2;

It provides only a limited number of data types may be used for bit field. In ANSI C, which is several data types int, signed int and unsigned int (int default is signed int); to C99, _Bool also supported.

Provided that if the type field of the same fields of adjacent bits, and the bit width less than the sum of sizeof type size, the back of the field immediately before a field store until it received so far. If the bit width which is larger than the sum of sizeof type size, the field starts from the back of the new storage unit for offset of an integer multiple of the size of the type;

status1的大小是4,因为12+20=32,没有超出int的最大长度
status2的大小是8,因为12+21=33,超出int的最大长度
/* 定义位域结构 */
struct
{
    unsigned int widthValidated : 12;
    unsigned int heightValidated : 20;

} status1;
/* 定义位域结构 */
struct
{
    unsigned int widthValidated : 12;
    unsigned int heightValidated : 21;

} status2;

Provided that if the type field adjacent bit field different from the specific implementation of each compiler differences, VC6, VS2019 compression is not adopted, Dev-C ++, GCC taken compression;

在VS中执行得到:Memory size occupied by status2 : 8
在Linux下GCC中执行得到:Memory size occupied by status2 : 4
struct
{
    unsigned int widthValidated : 12;
    bool heightValidated : 1;

} status2;

A predetermined overall size of the entire structure of the basic types of the widest member of an integer multiple of the size.

Provided that if the domain field interspersed with non-bit field between bit field, is not compressed;

struct
{
    unsigned int widthValidated : 12;
    double heightValidated ;
    unsigned int widthValidated1 : 14;
} status2;
Published 20 original articles · won praise 0 · Views 265

Guess you like

Origin blog.csdn.net/although1/article/details/104371159