Neel
Neel

Reputation: 10143

C program to set k lower order bits

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

Upvotes: 10

Views: 4192

Answers (4)

Graeme Perrow
Graeme Perrow

Reputation: 57248

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))
}

Upvotes: 19

Vinicius Kamakura
Vinicius Kamakura

Reputation: 7778

something along the lines of

set k lower bits:

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

Is that what you meant?

Upvotes: 1

Kijewski
Kijewski

Reputation: 26022

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.)

Upvotes: 10

Ed Bayiates
Ed Bayiates

Reputation: 11210

int bitmask = 1;
for (ix = 0;  ix < k;  ++ix)
{
    C = C | bitmask;
    bitmask <<= 1;
}

Upvotes: 1

Related Questions