kernelpanic kernelpanic - 1 month ago 5
C Question

Set last n bits in C

I wan't to set the last n bits of any given number to 1. I have a number (which is variable in it's lenght) and a variable n.


12 (dec) set last 2 bits
Output: 15

Now the basic operation should be something like:

return 0b11 | 12;

But how can I make 0b11 variable in length?

Thank you!


Try this:

int SetLastBits(int value,int numOfBits)
    return value | ((1<<numOfBits)-1);