kernelpanic kernelpanic - 1 year ago 100
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!

Answer Source

Try this:

int SetLastBits(int value,int numOfBits)
    return value | ((1<<numOfBits)-1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download