Chinaunix首页 | 论坛 | 博客
  • 博客访问: 803941
  • 博文数量: 489
  • 博客积分: 475
  • 博客等级: 下士
  • 技术积分: 3087
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 16:28
文章分类

全部博文(489)

文章存档

2013年(7)

2012年(301)

2011年(181)

分类:

2011-12-22 22:06:13

原文地址:位段 作者:luozhiyong131

  1. /*
  2.  *    位段的使用
  3.  *    Lzy        2011-5-29
  4.  */

  5. #include <stdio.h>

  6. struct status                        /*位段类型定义*/
  7. {
  8.     unsigned char bit1:    2;            /*定义bit1占2个二进制位,其范围0~8*/
  9.     unsigned char bit2:    2;            
  10.     unsigned char bit3:    2;
  11.     unsigned char bit4:    2;    
  12. };

  13. union Data                            /*定义联合体*/
  14. {
  15.     unsigned int x;
  16.     struct status Byte;
  17. };

  18. int main(void)
  19. {
  20.     union Data data = {0};        /*初始化*/

  21.     data.Byte.bit1 = 0x00;        /*第1、2位置00B*/
  22.     data.Byte.bit2 = 0x01;        /*第3、4位置01B*/
  23.     data.Byte.bit3 = 0x02;        /*第5、6位置10B*/
  24.     data.Byte.bit4 = 0x03;        /*第7、8位置11B*/

  25.     printf("%x\n",data.x);        /*data.x == 0xe4*/
  26. }
  1. /*
  2.  *    无名位段的使用
  3.  *    Lzy        2011-5-29
  4.  */

  5. #include <stdio.h>

  6. struct status                        /*位段类型定义*/
  7. {
  8.     unsigned int bit1:    4;            /*定义bit1占4个二进制位,其范围0~31*/
  9.     unsigned int     :    0;            /*定义长度为0的无名位段,其后续位段从下4个字节(int)开始存储*/    unsigned int bit3:    4;
  10.     unsigned int bit4:    4;    
  11. };

  12. union Data                            /*定义联合体*/
  13. {
  14.     int x[2];
  15.     struct status Byte;
  16. };

  17. int main(void)
  18. {
  19.     union Data data;
  20.     data.x[1] = 0x56;

  21.     printf("%d\n",data.Byte.bit3 + data.Byte.bit4);
  22. }
阅读(432) | 评论(0) | 转发(0) |
0

上一篇:C语言编程实例全。

下一篇:链表排序

给主人留下些什么吧!~~