Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set last `n` bits in unsigned int

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.

like image 229
Cartesius00 Avatar asked Nov 14 '11 21:11

Cartesius00


People also ask

How do you isolate the last bit?

To isolate any set of bits, apply an AND mask. If you want the last X bits of a value, there is a simple trick that can be used. unsigned mask; mask = (1 << X) - 1; lastXbits = value & mask; If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

How do you change the N bit of a number?

range = (((1 << (l - 1)) - 1) ^ ((1 << (r)) - 1)); 2. Now, perform "n = n | range". This will set the bits in the range from l to r in n.

How do I set up multiple bits?

to set the bit n of num (for instance num |= (1 << 0); sets the bit 0 ). To set (clear) multiple bits you have just to OR ( AND ) the num with the appropriate constant. num &= ~0xFF; clears the same bits.


2 Answers

Here's a method that doesn't require any arithmetic:

~(~0u << n)
like image 86
Eric Avatar answered Sep 18 '22 06:09

Eric


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.

like image 21
Marcelo Cantos Avatar answered Sep 21 '22 06:09

Marcelo Cantos