Miguel Pinto Miguel Pinto - 10 months ago 50
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 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

Answer Source

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