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

最佳答案

U表示“1”是无符号int,而不是潜在的有符号int。
here
至于另一个问题;我推测是-in CLR_标志引起了这个问题;请尝试使用“~”(按位不)。不过还没有测试过。

关于c - 位和字节操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3076799/

10-09 12:32