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;
}

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

 

上一篇:刷题记录--1bit与2bit字符


下一篇:范式霍夫曼编码