Search code examples
cbit

Activate some bits of a number in C


I need to 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).

So far I've came up with this:

int activate_bits(int a, int left, int right)
{
    int n, j, mask, masked_a;

    for (n = 1; n < left; n++) {
        mask = 1 << n;
        masked_a = a | mask;
    }

    for (j = 31; j > right; j--) {
        mask = 1 >> j;
        masked_a = a | mask;
    }

    return masked_a;
}

Can anyone help me to why the masked_a it's not correct or fix my faulty code?


Solution

  • I suspect you need to be setting masked_a to a before looping:

    int activate_bits(int a, int left, int right)
    {
        int n, j, mask, masked_a;
    
        masked_a = a;
    
        for (n = 0; n < left; n++) {
            mask = 0x80000000 >> n;
            masked_a = masked_a | mask;
        }
    
        for (j = 0; j < right; j++) {
            mask = 1 << j;
            masked_a = masked_a | mask;
        }
    
        return masked_a;
    }
    

    EDIT: I've updated the loops to what I think are correct, although that is open to interpretation depending on what the expected answer is. Apologies for the earlier incorrect response, I was just pointing out the glaring error and that should probably have been a comment.