Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program to set k lower order bits

For a 32 bit integer, how do I set say k low order bits in C?

like image 963
Neel Avatar asked Jun 21 '11 00:06

Neel


3 Answers

Assuming you want to set the k lowest bits of a 32-bit integer x, I believe this will work:

if( k > 0 ) {
    x |= (0xffffffffu >> (32-k))
}
like image 200
Graeme Perrow Avatar answered Oct 13 '22 19:10

Graeme Perrow


To set n least significant bits in k, you could use arithmetic:

k |= (1 << n) - 1;

(Provided n is less or equal your int size in bits.)

like image 10
kay Avatar answered Oct 13 '22 21:10

kay


something along the lines of

set k lower bits:

while (k) {
    k--;
    num |= (1<<k);
}

Is that what you meant?

like image 1
Vinicius Kamakura Avatar answered Oct 13 '22 20:10

Vinicius Kamakura