C Language Learning Series: Bit field

The so-called "bit field" is the binary one byte is divided into several different regions, and indicate the number of bits of each area. Each domain has a domain name, the program allows the press to operate in the domain. This allows several different objects to be represented by a byte bit field.

Bit field declaration

struct bitFieldName
{
  type [member_name] : width ;
}exampleVar;

When the definition of body structure, we can specify a member variable occupied by the number of bits (Bit), this is the bit field.

It can not exceed the width of the field of the data types 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.

Only a limited number of data types may be used for bit field. These types of data types are int, signed int and unsigned int, _Bool. But in the specific compiler implementations has been extended, additional support for the char, signed char, unsigned char and enum types.

Bitfield storage

DETAILED bit field storage rule is as follows:
1. When the same type of the adjacent members, if they are less than the sum of the bit width of sizeof type size, the former member immediately behind a storage member, until it received so far; if their type bit width greater than the sum of sizeof size, the members of the latter will start a new storage unit, an offset of an integer multiple of the size of the type.

#include <stdio.h>
int main(){
    struct bs{
        unsigned m: 6;
        unsigned n: 12;
        unsigned p: 4;
    };
    printf("%d\n", sizeof(struct bs));
    return 0;
}

2. When the adjacent members are different types, different compilers have different implementations, GCC  will be compressed storage, and VC / VS will not.

#include <stdio.h>
int main(){
    struct bs{
        unsigned m: 12;
        unsigned char ch: 4;
        unsigned p: 4;
    };
    printf("%d\n", sizeof(struct bs));
    return 0;
}

3. If interspersed with non-bit field members among members, it will not be compressed.

#include <stdio.h>
int main(){
    struct bs{
        unsigned m: 12;
        unsigned ch;
        unsigned p: 4;
    };
    printf("%d\n", sizeof(struct bs));
    return 0;
}

Bit field members often do not take full byte, sometimes not in the beginning byte position, so using &the address acquisition bit field members is meaningless, C language is also prohibited from doing so. Address byte (Byte) numbers, instead of a bit (Bit) number.

Unnamed bit field

Bit field members may not have names, and give only the data type bits wide, unnamed bitfield generally used as a filler or adjust the position of the members. Because there is no name, unnamed bit field can not be used.

struct bs{
    int m: 12;
    int  : 20;  //该位域成员不能使用
    int n: 4;
};
发布了161 篇原创文章 · 获赞 90 · 访问量 5万+

Guess you like

Origin blog.csdn.net/qq_42415326/article/details/104027386