# 学点 C 语言(27): 数据类型 - 结构中的 "位字段"

1. 结构体可以包含位字段:
#include <stdio.h>

int main(void)
{
struct Bit {
unsigned a: 1; /* 1 Bit, 取值范围: 0 - 1  */
unsigned b: 2; /* 2 Bit, 取值范围: 0 - 3  */
unsigned c: 3; /* 3 Bit, 取值范围: 0 - 7  */
unsigned d: 4; /* 4 Bit, 取值范围: 0 - 15 */
} B;

B.a = 1;
B.b = 3;
B.c = 7;
B.d = 15;

printf("%d, %d, %d, %d\n", B.a, B.b, B.c, B.d);

getchar();
return 0;
}



11111111B = 255;
00000001B = 1;
00001111B = 15;
01111111B = 127;

2. 用 8 个 Bit 构成一个 unsigned char 数:
#include <stdio.h>

int main(void)
{
struct Bit {
int b8: 1;
int b7: 1;
int b6: 1;
int b5: 1;
int b4: 1;
int b3: 1;
int b2: 1;
int b1: 1;
} B;

unsigned char *p = NULL;

B.b1 = 1; B.b2 = 1; B.b3 = 1; B.b4 = 1; B.b5 = 1; B.b6 = 1; B.b7 = 1; B.b8 = 1;
p = (unsigned char *)&B;
printf("%d\n", *p);  /* 255 */

B.b1 = 0; B.b2 = 0; B.b3 = 0; B.b4 = 0; B.b5 = 0; B.b6 = 0; B.b7 = 0; B.b8 = 1;
p = (unsigned char *)&B;
printf("%d\n", *p);  /* 1   */

B.b1 = 0; B.b2 = 0; B.b3 = 0; B.b4 = 0; B.b5 = 1; B.b6 = 1; B.b7 = 1; B.b8 = 1;
p = (unsigned char *)&B;
printf("%d\n", *p);  /* 15  */

B.b1 = 0; B.b2 = 1; B.b3 = 1; B.b4 = 1; B.b5 = 1; B.b6 = 1; B.b7 = 1; B.b8 = 1;
p = (unsigned char *)&B;
printf("%d\n", *p);  /* 127 */

getchar();
return 0;
}



3. 包含位字段的结构和其他结构没有区别, 譬如同时包含其他类型的字段:
#include <stdio.h>

int main(void)
{
struct Bit {
unsigned b1: 1;
unsigned b2: 1;
float f;
} B;

B.b1 = 0;
B.b2 = 1;
B.f = 3.14;

printf("%d, %d, %g\n", B.b1, B.b2, B.f);

getchar();
return 0;
}



posted on 2008-11-28 21:40  万一  阅读(...)  评论(...编辑  收藏