Masking bits within a range given in parameter in C

前端 未结 4 930
忘了有多久
忘了有多久 2020-12-07 05:55

I am new to C programming and not sure that there is already a good explanation for how to do this, if so I am sorry. I am trying to set the bits within a range given to me.

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 06:05

    This was my solution: The if statements at the front just cover conditionals about low and high. This is passing all the tests I was given.

    unsigned int setBits(int low, int high, unsigned int source)
     {
     if (low < 0)         {return source;}
     else if (high > 31)  {return source;}
     else if (low > high) {return source;}
     else {
             unsigned int mask = 0xFFFFFFFF << (31 - high);
             mask = mask >> ((31 - high) + low);
             mask = mask << low;
             return source | mask;
         }        
    

    }

提交回复
热议问题