试图在C中执行按位操作,意外结果

时间:2016-11-19 18:40:31

标签: c bit-manipulation

所以我现在正在努力完成一些处理按位操作的大学作业,其中一个练习给我带来了最糟糕的麻烦,那就是你不知道哪里出错了。练习如下:

  

实现应该'激活'的函数int activate_bits(int a,int left,int right)   数字a左边和右边的所有位(不包括位   左右)。

我关于activate_bits函数的代码如下

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

}

任何人都可以帮助我,为什么这会给我一个错误的结果? 提前致谢

2 个答案:

答案 0 :(得分:2)

mask1 << 1;并不能按照您的想法行事。它不像mask1++增加mask1;它与行mask1 + 1相同 - 评估结果但不存储在任何地方。

尝试这样做:

mask1 = mask1 << 1

或者,为了简洁起见:

mask1 <<= 1

答案 1 :(得分:2)

你可以在没有任何循环的情况下简化整个事情:

unsigned int activate_bits(int a, int left, int right)
{
    unsigned int mask1;
    unsigned int mask2;
    unsigned int tmp;


    // left mask
    tmp = 0x01 << left;         // e.g. if left is 15, then set bit #15 ...  tmp=0x00008000
    tmp = tmp - 1;              // set bits 0-15, and left bit 15 cleared:   0x00008000 => 0x0007fff
    tmp = ~tmp;                 // invert the bits:  0x00007fff ===> 0xffff8000
    tmp = tmp << 1;             // clear bit 15
    mask1 = tmp;                // and that's the left mask

    // right mask
    tmp = 0x01 << right;      // If right is 15, start by setting the 15 bit... tmp = tmp=0x00008000
    tmp = tmp - 1;            // clear bit 15 and set everything to the right of it. 0x00008000 ===> 0x00007fff;
    mask2 = tmp;

    return (a | mask1 | mask2);
}