Miguel Pinto - 1 year ago 73
C Question

# Attempting to perform a bitwise manipulation in C, unexpected results

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 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++){

}

/* 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--){

}

/* 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 */

}
``````

Can anyone help me as to why this is giving me a wrong result ?

`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.
`mask1 = mask1 << 1`
`mask1 <<= 1`