位和字节操作

时间:2010-06-19 18:49:56

标签: c

/* 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) 请澄清.... 谢谢。

3 个答案:

答案 0 :(得分:2)

U意味着'1'是无符号的int,而不是可能签名的int。

请参阅here

至于另一个问题;我推测CLR_FLAG中的 - 导致问题;尝试使用'〜'(不按位)。虽然没有测试过这个。

答案 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)

如果您确实想要在大写和小写之间更改字符,则不应该这样做。请改用toupper() / tolower()。通过使用这些例程,您的意图更加清晰,并且考虑了大写/小写字符的任何区域设置特定差异。