智能车制作

标题: CW中变量位操作的另一种高效方法[原创] [打印本页]

作者: whut_wj    时间: 2009-9-15 08:18
标题: CW中变量位操作的另一种高效方法[原创]
大家熟知的51有位定义和位操作符,但非常不利用程序的移植,现在的很多控制处理器都不用了.飞思的也不支持这种位操作.
   这里介绍一种方法,对变量的位直接进行操作,不用"与""非""或"运算:
   通过将一个变量的地址强行绑定在一个位段的指针上,并通过该指针来访问位段,实现对该变量任意二进制位单独操作.
DATABit,例如,我要操作DATABit的第4位,怎么实现呢?
typedef struct
{
    unsigned bit0 :1;
    unsigned bit1 :1;
    unsigned bit2 :1;
    unsigned bit3 :1;
    unsigned bit4 :1;
    unsigned bit5 :1;
    unsigned bit6 :1;
    unsigned bit7 :1;
}BYTE2BIT;

byte DATABit;
void main(void) {

  EnableInterrupts; /* enable interrupts */
  /* include your code here */

  (*((BYTE2BIT*)(&DATABit))).bit4=1;


  for(;;) {
    __RESET_WATCHDOG(); /* feeds the dog */
  } /* loop forever */
  /* please make sure that you never leave main */
}

   对于byte变量DataBit,表达式先通过"&"运算获得其地址.
   接下来,将这一地址的类型强行绑定为指向位域Byte2Bit的指针
   最后,利用指针操作符"*",就可以对DataBit变量的任何一个二进制位了.
  关于位操作的那些说明,还可以参考张明峰的个IDE介绍.这里不多说.

http://blog.eccn.com/space.php?uid=353091&do=blog&id=1043
作者: 小雨1111    时间: 2010-1-6 21:22
真的不错
作者: 小雨1111    时间: 2010-1-6 21:23
真的不错
作者: maxhai    时间: 2010-1-19 14:25
在51上能这么用么??
作者: maxhai    时间: 2010-1-19 14:25
在51上能这么用么??
作者: cyningmi    时间: 2012-5-14 13:14
typedef struct byte
{
    unsigned bit0 :1;
    unsigned bit1 :1;
    unsigned bit2 :1;
    unsigned bit3 :1;
    unsigned bit4 :1;
    unsigned bit5 :1;
    unsigned bit6 :1;
    unsigned bit7 :1;
}Bitbyte;
Bitbyte example;
example.4=1;




欢迎光临 智能车制作 (http://111.231.132.190/) Powered by Discuz! X3.2