c语言中按位逻辑运算符、位移运算符

2021-05-28 15:01

阅读:360

标签:clu   please   NPU   bin   can   char   scanf   print   src   

c语言中按位逻辑运算符、位移运算符

#include 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);
}

int 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 unsigned integers.");
    printf("a = "); scanf("%u", &a);
    printf("b = "); scanf("%u", &b);
    
    printf("\nbinary a   = "); print_bits(a);
    printf("\nbinary b   = "); print_bits(b);
    printf("\na  &   b   = "); print_bits(a & b);
    printf("\na  |   b   = "); print_bits(a | b);
    printf("\na  ^   b   = "); print_bits(a ^ b);
    printf("\n ~a        = "); print_bits(~a);
    printf("\n ~b        = "); print_bits(~b);
    
    return 0;
}

技术图片

 

c语言中按位逻辑运算符、位移运算符

标签:clu   please   NPU   bin   can   char   scanf   print   src   

原文地址:https://www.cnblogs.com/liujiaxin2018/p/14780438.html


评论


亲,登录后才可以留言!