hektor - 1 year ago 80
C Question

# How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Could anyone tell me as to how to extract 'n' specific bits from a 32-bit unsigned integer in C.

For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?

I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits as

``````unsigned last8bitsvalue=(32 bit integer) % 16
unsigned last16bitsvalue=(32 bit integer) % 32
``````

Is this correct? Is there a better and more efficient way to do this?

If you want n bits specific then you could first create a bitmask and then `AND` it with your number to take the desired bits.

Simple function to create mask from bit a to bit b.

``````unsigned createMask(unsigned a, unsigned b)
{
unsigned r = 0;
for (unsigned i=a; i<=b; i++)
r |= 1 << i;

return r;
}
``````

You should check that a<=b.

If you want bits 12 to 16 call the function and then simply & (logical AND) `r` with your number `N`

``````r = createMask(12,16);
unsigned result = r & N;
``````

If you want you can shift the result. Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download