Question: How to set (in most elegant way) exactly `n` least significant bits of `uint32_t`? That is to write a function `void setbits(uint32_t *x, int n);`. Function should handle each `n` from `0` to `32`.

Especially value `n==32` should be handled.

Answer: 
If you meant the least-significant n bits:

```
((uint32_t)1 << n) - 1

```

On most architectures, this won't work if n is 32, so you may have to make a special case for that:

```
n == 32 ? 0xffffffff : (1 << n) - 1

```

On a 64-bit architecture, a (probably) faster solution is to cast up then down:

```
(uint32_t)(((uint64_t)1 << n) - 1)

```

In fact, this might even be faster on a 32-bit architecture since it avoids branching.
If n is zero then no bits should be set based on the question.

```
const uint32_t masks[32] = {0x1, 0x3, 0x7, ..., 0xFFFFFFFF};

void setbits(uint32_t *x, int n)
{
    if ( (n > 0) && (n <= 32) )
    {
        *x |= masks[--n];
    }
}

```