位段
位段:
用法:
typedef struct {
unsigned char Bit0:1; // 占据的位的个数
unsigned char Bit1:1;
unsigned char Bit2:1;
unsigned char Bit3:1;
unsigned char Bit4:1;
unsigned char Bit5:1;
unsigned char Bit6:1;
unsigned char Bit7:1;
}strBit;
#define Set_Bit0 0x00000001
#define Set_Bit1 0x00000002
#define Set_Bit2 0x00000004
#define Set_Bit3 0x00000008
#define Set_Bit4 0x00000010
#define Set_Bit5 0x00000020
#define Set_Bit6 0x00000040
#define Set_Bit7 0x00000080
Unsigned char arry[3];
然后即可位寻址 (strBit*(arry+0))->Bit0=Set_Bit0
联合体与位段:在处理协议方面很方便。
ttypedef struct
{
uchar name;
uchar age
union
{
uchar byte;
struct
{
uchar sex:1;
uchar color:1;
uchar reserved:6;
}BIT;
}personal
}peple
Peple *Pchinese; //结构体指针
Uchar arrybuf[n];//公共缓冲区
Chinese=( Peple *)arraybuf;
Pchinese-〉personal->BIT.sex=0;
注意:如果定义的位超过8位,要注意大小端的问题:
在keil中如果要定义12和位变量,假如其值为0x0f3f,则应该这样定义
typedef union
{
unsigned short int Halfword;
struct
{
unsigned char BIT8:1 ; /*高字节在前0x0f,每字节的位顺序由低到高*/
unsigned char BIT9:1 ;
unsigned char BIT10:1 ;
unsigned char BIT11:1 ;
unsigned char reserved:4;/*右對齊*/
unsigned char BIT0:1 ;/*低字节在后0x3f,每字节的位定义顺序由低到高*/ /*1*/
unsigned char BIT1:1 ;/*1*/
unsigned char BIT2:1 ; /*1*/
unsigned char BIT3:1 ;/*1*/
unsigned char BIT4:1 ;/*1*/
unsigned char BIT5:1 ;/*1*/
unsigned char BIT6:1 ;/*0*/
unsigned char BIT7:1 ; /*0*/
}strBits;
}Chstatus_typeDef;
C51中比较实用的位段用法:
在基本数据类型头文件data_type.h中这样定义:
typedef struct
{
unsigned char BIT0:1;
unsigned char BIT1:1;
unsigned char BIT2:1;
unsigned char BIT3:1;
unsigned char BIT4:1;
unsigned char BIT5:1;
unsigned char BIT6:1;
unsigned char BIT7:1;
}strBits;
在要使用位段的模块中
1 先#include "data_type.h"
2 定义具体的变量:strBits xdata XXX_Flags;
3定义每个位变量:
#define flag_s0 XXX_Flags.BIT0
#define flag_s1 XXX_Flags.BIT1
#define flag_s2 XXX_Flags.BIT2
#define flag_s3 XXX_Flags.BIT3
#define flag_s4 XXX_Flags.BIT4
#define flag_s5 XXX_Flags.BIT5
#define flag_s6 XXX_Flags.BIT6
#define flag_s7 XXX_Flags.BIT7
但是这样的话外部声明很难做,折中的办法是在aa.h中
#include datatype.h
#ifdef MAIN_Value_GLOBALS
#define MAIN_EXT
#else
#define MAIN_EXT extern
#endif
MAIN_EXT strBits My_FlagData ;
#define flag_s0 My_FlagData.BIT0
#define flag_s1 My_FlagData.BIT1
#define flag_s2 My_FlagData.BIT2
#define flag_s3 My_FlagData.BIT3
#define flag_s4 My_FlagData.BIT4
#define flag_s5 My_FlagData.BIT5
#define flag_s6 My_FlagData.BIT6
#define flag_s7 My_FlagData.BIT7
在aa.c中#define MAIN_Value_GLOBALS 然后包含aa.h
在bb.c中包含aa.h就可以直接引用了。