《明解C语言(入门篇)》练习7-4

/*
编写set函数,返回将无符号整数x的第pos位设为1后的值
编写reset函数,返回将无符号整数x的第pos位设为0后的值
编写inverse函数,返回将无符号整数x的第pos位取反后的值
*/

#include <stdio.h>

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

int int_bits()
{
    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');
}

unsigned set(unsigned x, int pos)
{
    return x | 1U << pos - 1;
}

unsigned reset(unsigned x, int pos)
{
    return x & ~(1U << pos - 1);
}

unsigned inverse(unsigned x, int pos)
{
    return x ^ 1U << pos - 1;
}

int main()
{
    unsigned xx;
    int x_pos, selected;

    printf("1>>>某一位设为1\n2>>>某一位设为0\n3>>>某一位取反\n请选择对应的数字:");
    scanf("%d", &selected);

    printf("请输入一个非负整数:"); scanf("%u", &xx);

    if (selected == 1)
        printf("请输入第几位设为1:");
    else if (selected == 2)
        printf("请输入第几位设为0:");
    else
        printf("请输入第几位取反:");
    
    scanf("%d", &x_pos);

    printf("更改前:");
    print_bits(xx);
    putchar('\n');

    printf("更改后:");
    if (selected == 1)
        print_bits(set(xx, x_pos));
    else if (selected == 2)
        print_bits(reset(xx, x_pos));
    else
        print_bits(inverse(xx, x_pos));
    
    return 0;
}
上一篇:使用Python翻转数组中的位


下一篇:程序员欢乐送(第20期)