C语言位运算题解

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#define NONBLANK 1
main()
{
    /* 位运算 */
    int n;
    printf("开始启动程序:
");
    printf("开始调用函数:
");
    int setbits(int, int, int, int);
    int result = setbits(10, 4, 3, 3);
    printf("结果等于%d", result);
    system("pause");
    return 0;
}
/* 将x中从p开始右边的n位设置为y中右边n位的值,返回结果 */
int setbits(int x, int p, int n, int y)
{
    int old_x = x & ~(~0 << p-n+1);  //先将x中移出去的那p-n+1位保存起来
    /*  为了方便,这里先以16位为例
        以10举例:0000 0000 0000 1010
        x=10, p=4, n=3, y=2
        因为位数是从右往左数,并且从0开始,所以右移的时候,p-n要加上1才对
        old_x:也就是 0000 0000 0000 0010
    */
    int new_x = (x >> p - n + 1) | ~(~0 << n);  //x中除了p位开始到右边n位,其余位保持不变,如何保持不变?“和1与”、“和0或”都能保持不变
    // new_x = 0000 0000 0000 0010 | 0000 0000 0000 0111
    // new_x = 0000 0000 0000 0111  ----再把y的值变成除了右边n位不变,其余位都变成1,这样new_x和y按位与就得出结果了
    //注意:如果想和y按位或,就得让new_x右边n位都是0才行。这样得出的结果和上面的一样。但是后面的处理可能更麻烦一些。
    int new_y = y | (~0 << n);
    int result = new_x & new_y;
    result = result << p - n + 1;   //恢复原来的位置
    result = result | old_x;  //最终结果
    return result;
}

这是C语言书中的一道题。

原文地址:https://www.cnblogs.com/bneglect/p/11885919.html