c语言中按位逻辑运算符的使用

1、

#include <stdio.h>

int count_bits(unsigned x)
{
    int bits = 0;
    while(x)
    {
        if(x & 1U)
            bits++;
        x >>= 1;
    }
    return bits;
}

int int_bits(void)
{
    return count_bits(~0U);
}

void print_bits(unsigned x)
{
    int i;
    for(i = int_bits() - 1; i >= 0; i--)
    {
        putchar((x >> i & 1U) ? '1' : '0');
    }
    putchar('\n');
}

int main(void)
{
    unsigned a, b;
    puts("please input two nonnegative numbers.");
    printf("a = "); scanf("%u", &a);
    printf("b = "); scanf("%u", &b);
    
    printf("binary a     = "); print_bits(a);
    printf("binary b     = "); print_bits(b);
    printf("a & b        = "); print_bits(a & b);
    printf("a | b        = "); print_bits(a | b);
    printf("a ^ b        = "); print_bits(a ^ b);
    printf("~a           = "); print_bits(~a);
    printf("~b           = "); print_bits(~b);
    
    return 0;
}

 

posted @ 2021-05-21 09:15  小鲨鱼2018  阅读(220)  评论(0编辑  收藏  举报