1. 程式人生 > >在C語言中bit field 位域

在C語言中bit field 位域

在C語言中bit feild 位域.

A bit field declaration is a struct or union member declaration。

an integer constant expression with a value greater or equal to zero and less or equal the number of bits in the underlying type.
When greater than zero, this is the number of bits that this bit field will occupy.
當位域長度大於零時,將使用n個位作為位域長度。
The value zero is only allowed for nameless bitfields and has special meaning: it specifies that the next bit field in the class definition will begin at an allocation unit's boundary.
當位域的長度為零時,以為這下一個位域將從下一個單元的邊界開始。


Bit fields can have only one of four types :

1、unsigned int, for unsigned bit fields (unsigned int b:3; has the range 0..7)
unsigned int型別位域; (例如 unsigned int b:3 範圍為0-7)

2、signed int, for signed bit fields (signed int b:3; has the range -4..3)
有符號整型位域。(signed int b:3;儲存範圍為-4-3)

3、int, for bit fields with implementation-defined。 For example, int b:3; may have the range of values 0..7 or -4..3.
int型別位域標準由編譯器實現。例如:int b:3.位域範圍為0-7或者-4 -3.

4、_Bool, for single-bit bit fields (bool x:1; has the range 0..1)

注意:
Whether bit fields of type int are treated as signed or unsigned
Whether types other than int, signed int, unsigned int, and _Bool are permitted 。
在C語言標準中,int作為無符號位域或者有符號位域由編譯器實現。
其他基本型別作為位域的型別是被允許的。由編譯器自己實現。

struct S_uInt
{
 // three-bit unsigned field,
 // allowed values are 0...7
 unsigned int b : 3;
 unsigned int c : 3;

};
struct S_zero
{
    // will usually occupy 8 bytes:
    // 5 bits: value of b1
    // 27 bits: unused
    // 6 bits: value of b2
    // 15 bits: value of b3
    // 11 bits: unused
    unsigned int b1 : 5;
    unsigned int :0; // start a new unsigned int
    unsigned int b2 : 6;
    unsigned int b3 : 15;
    
};

struct S_uInt s = {7,7};
    printf("%d\n",sizeof(S_uInt));
    printf("%d\n", s.b); // output: 0
    printf("%d\n", s.c); // output: 0
    ++s.b; // unsigned overflow
    printf("%d\n", s.b); // output: 0

    printf("%d\n",sizeof(S_zero));