Reputation: 19
So I'm currently trying to finish some university homework that deals with bitwise manipulations, and one of the exercises is giving me the worst kind of trouble, the one where you dont know where you went wrong. The exercise is as follows:
Implement the function int activate_bits(int a, int left, int right ) that should ’activate’ all the bits to the left of left and to the right of right on the number a (excluding the bits left and right).
My code regarding the activate_bits function is the following
#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;
}
Can anyone help me as to why this is giving me a wrong result ? Thanks in advance
Upvotes: 0
Views: 148
Reputation: 104474
You can simplify the whole thing without any loops:
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);
}
Upvotes: 2
Reputation: 21532
mask1 << 1;
doesn't do what you think it does. It's not like mask1++
which increments mask1
; it's the same as having the line mask1 + 1
- the result is evaluated but not stored anywhere.
Try doing this:
mask1 = mask1 << 1
Or, for brevity's sake:
mask1 <<= 1
Upvotes: 2