本文主要是介绍在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));
这篇关于在C语言中bit field 位域的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!