Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 391
hektor Avatar asked Nov 04 '11 15:11

hektor


People also ask

How many bits are in an unsigned int?

An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295].

How many bits is a 32-bit integer?

How many integers can be represented in 32 bits? Using 32 bits up to 4,294,967,296 pieces of unique data can be stored. As signed integers, the range is -2,147,483,648 to 2,147,483,647.

How do you find the range of a bit?

You can work the number of values quickly by calculating 2n, where n is the number of bits available, for example 28 = 256 values. The range of values is from 0 to 2n – 1, for example 0 to 28 – 1 = 0—255.


2 Answers

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

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

unsigned  mask; mask = ((1 << X) - 1) << startBit; isolatedXbits = value & mask; 

Hope this helps.

like image 85
Sparky Avatar answered Oct 11 '22 18:10

Sparky


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

like image 23
pnezis Avatar answered Oct 11 '22 18:10

pnezis