Reputation: 10143
For a 32 bit integer, how do I set say k low order bits in C?
Upvotes: 10
Views: 4192
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
Reputation: 7778
something along the lines of
set k lower bits:
while (k) {
k--;
num |= (1<<k);
}
Is that what you meant?
Upvotes: 1
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
Reputation: 11210
int bitmask = 1;
for (ix = 0; ix < k; ++ix)
{
C = C | bitmask;
bitmask <<= 1;
}
Upvotes: 1