所以我现在正在努力完成一些大学作业,这些作业涉及按位操作,其中一个练习给我带来了最严重的麻烦,就是你不知道哪里出错了。练习如下:
实现函数int activate_bits(int a,int left,int right),该函数应该“activate”
数字a左、右的所有位(不包括位
左右)。
关于激活位功能的代码如下

#include <stdio.h>

unsigned int activate_bits(unsigned a, int left, int right){

int mask1 = 1;
int mask2 = 1;
int mask3 = 0;

int i;

/* assuming an int as only 8 bits for convenience, what I want to do here is
shift the least significant bit to the left, then add 1,as many times as
necessary(according to the parameter right), so that the number 00000001
becomes 00000011 and so forth */

for (i= (right -1); i<right ; i++){

    mask1 << 1;
    mask1 = mask1 +1 ;

}

/* doing the same as above here, checking how many activated bits the second
mask should actually have by doing (32 - left ) */

for (i = (32 - left); i < 0; i--){

    mask2 << 1;
    mask2 = mask2 +1 ;

}

/* now I'm shifting the second mask as many times as needed so it is placed
after the bit position indicated by the left parameter */

mask2 << left;

mask3 = mask1 + mask2;

return a | mask3;

}

有人能帮我解释一下为什么这会给我一个错误的结果吗?
提前谢谢

最佳答案

mask1 << 1;并不像你想象的那样。这不像mask1++是递增的;它和有行mask1是一样的——结果是计算出来的,但不存储在任何地方。
尝试这样做:
mask1 + 1
或者,为了简洁起见:
mask1 = mask1 << 1

关于c - 尝试在C中执行按位操作,结果异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40696577/

10-11 19:18