位域,段域,联合体,结构体操作寄存器

来源:互联网 发布:美国债券市场托管数据 编辑:程序博客网 时间:2024/06/06 15:43
#include <stdio.h>typedef int Uint16;struct  SCICCR_BITS {        // bit    description   Uint16 SCICHAR:3;         // 2:0    Character length control           Uint16 ADDRIDLE_MODE:1;   // 3      ADDR/IDLE Mode control   Uint16 LOOPBKENA:1;       // 4      Loop Back enable   Uint16 PARITYENA:1;       // 5      Parity enable      Uint16 PARITY:1;          // 6      Even or Odd Parity   Uint16 STOPBITS:1;        // 7      Number of Stop Bits   Uint16 rsvd1:8;           // 15:8   reserved}; union SCICCR_REG {   Uint16              all;   struct SCICCR_BITS  bit;};extern int a =0 ;//定义一个全局变量a 并给初值。extern int b;   //声明一个变量,在别处定义了int main(int argc,char *argv[]){    union SCICCR_REG SCIICR;    a=1;    printf("a=%d\n",a);    SCIICR.all=0xfe;    printf("SCIICR=%x\n",SCIICR);    SCIICR.bit.SCICHAR=0b000;    printf("SCIICR=%x\n",SCIICR);    return 0;}


输出结果:

 

a=1
SCIICR=fe
SCIICR=f8


/usercode/file.cpp:19:12: warning: ‘a’ initialized and declared ‘extern’ [enabled by default]
 extern int a =0 ;//定义一个全局变量a 并给初值。
            ^
/usercode/file.cpp: In function ‘int main(int, char**)’:
/usercode/file.cpp:27:32: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘SCICCR_REG’ [-Wformat=]
     printf("SCIICR=%x\n",SCIICR);
                                ^
/usercode/file.cpp:29:32: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘SCICCR_REG’ [-Wformat=]
     printf("SCIICR=%x\n",SCIICR);
                                ^
分析:union SCICCR_REG {  

                                                Uint16              all;  

                                                 struct SCICCR_BITS  bit;

                                              };

实现了想进行整体操作时就进行整体操作,想进行位操作时就进行位操作。

注意操作时,位域在内存中的高低排序,先定义的位域在内存地址低处。

 

 

 

 

 

 

 

原创粉丝点击