/* Bit Masking */
/* Bit masking can be used to switch a character between lowercase and uppercase */
#define BIT_POS(N) ( 1U << (N) )
#define SET_FLAG(N, F) ( (N) |= (F) )
#define CLR_FLAG(N, F) ( (N) &= -(F) )
#define TST_FLAG(N, F) ( (N) & (F) )
#define BIT_RANGE(N, M) ( BIT_POS((M)+1 - (N))-1 << (N) )
#define BIT_SHIFTL(B, N) ( (unsigned)(B) << (N) )
#define BIT_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 <stdio.h>
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, BIT_POS(5)) );
printf(“Turn 5th bit off = %c\n\n”, CLR_FLAG(ascii_char, BIT_POS(5)) );
printf(“Look at shifting bits\n”);
printf(“=====================\n”);
printf(“Current value = %d\n”, test_nbr);
printf(“Shifting one position left = %d\n”,
test_nbr = BIT_SHIFTL(test_nbr, 1) );
printf(“Shifting two positions right = %d\n”,
BIT_SHIFTR(test_nbr, 2) );
}
在上面的代码中,你在
中的意思是什么#define BIT_POS(N) ( 1U << (N) )
此外,上述程序编译正常,输出
Starting character = A
Turn 5th bit on = a
Turn 5th bit off = `
Look at shifting bits
=====================
Current value = 10
Shifting one position left = 20
Shifting two positions right = 5
但是当第5位关闭时,结果必须是A而不是`(ascii 96) 请澄清.... 谢谢。
答案 0 :(得分:2)
答案 1 :(得分:2)
问题出在这一行:
#define CLR_FLAG(N, F) ( (N) &= -(F) )
CLR_FLAG
宏按位进行,N
和-F
进行。也就是说,N
和减号 - F
。你真正想要做的是使用F
的按位补码:
#define CLR_FLAG(N, F) ( (N) &= ~(F) )
请注意,现在我使用~F
。 ~
运算符按位not
执行。
答案 2 :(得分:0)