flags&1;
为了置位所需的位,可以让数据和屏蔽字进行按位或操作(C的按位或运算符为|)。例如,你可以这样置位flags的最低位:
flags = flags | 1;
或者这样:
flags |= 1;
为了清除所需的位,可以让数据和对屏蔽字按位取反所得的值进行按位与操作。例如,你可以这样清除flags的最低位:
flags = flags& ~1;
或者这样:
flags&=~1 ;
有时,用宏来处理标志会更方便,例10.2中的程序就是通过一些宏简化了位操作。
例10.2 能使标志处理更方便的宏
/* Bit Masking * /
/ * Bit masking can be used to switch a character
between lowercase and uppercase * /
#define B99v_POS(N) ( 1U (N) )
#define SET_FLAG(N,F) ( (N) | = (F) )
#define CLR_FLAG(N,F) ( (N) &= - (F) )
#define TST_FLAGCN,F) ( (N) & (F) )
#define B99v_RANGE(N,M) ( B99v_POS((M) + 1- (N))-1<<(N))
#define B99v_SHIFTL(B,N) ( (unsigned)(B)(N) )
#define B99v_SHIFTR(B,N) ( (unsigned)(B)(N) )
#define SET_MFLAG(N,F,V) ( CLR_FLAG(N,F), SET_FLAG(N,V) )
#define CLR_MFLAG(N,F) ( (N) &= ~(F) )
#define GET_MFLAG(N,F) ( (N) & (F) )
# include
void main()
{
unsigned char ascii_char = 'A'; /* char = 8 bits only */
int test_nbr = 10;
printf("Starting character = %c/n" , ascii_char);
/" The 5th bit position determines if the character is
uppercase or lowercase.
5th bit = 0 - Uppercase
5th bit = 1- Lowercase * /
printf ("/nTurn 5th bit on = %c/n" , SET_FLAG(ascii_char, B99v_POS(5)));
printf ("Turn 5th bit off = %c/n/n",CLR_FLAG(ascii_char, B99v_POS(5)));
printf ("Look at shifting bits/n");
printf (" = = = = = = = = = = = = = = = =/n" );
printf ("Current value = %d/n" , test_nbr)i
printf ("Shifting one position left = %d/n" ,
test_nbr = B99v_SHIFTL(test_nbr, 1) );
printf ("Shifting two positions right = %d/n" ,
B99v_SHIFTR(test_nbr, 2) );
}
宏B99v_POS(N)能返回一个和N指定的位对应的屏蔽字(例如B99v_POS(O)和B99v_POS(1)分别返回最低位和倒数第二位的屏蔽字),因此你可以用
#define A_FLAG B99v_POS(12)
&nb