How to extract specific bits from a number in C?

2019-01-22 03:22发布

I need to extract specific part (no of bits) of a short data type in C.

For Example I have a binary of 52504 as 11001101000 11000 and I want First 6 ( FROM LSB --> MSB i.e 011000 decimal 24) bits and rest of 10 bits ( 11001101000 decimal 820).

Similarly I want this function to be too generalized to extract specific no of bits given "start" and "end" (i.e chunks of bits equivalent with some decimal value).

I checked other posts, but those were not helpful, as given functions are not too much generalized.

I need something that can work for short data type of C.

Edit

I am having the short array of size 2048 bytes. Where each Pixel is of 10 bits. So my 16 bit consisting each byte occupying some time 2 pixels data, sometimes 3 pixels data.

Like

( PIXEL : 0,1 ) 10 BITS + 6 BITS

then ( PIXEL : 1,2,3 ) 4 BITS ( 1st pixels remaining bits ) + 10 BITS + 2 BITS.

and so on ..this pattern continues ... So, all I want to extract each pixel and make an entire array of having each pixels to be occupied wholy in on WHOLE BYTE ( of 16 bits ) like.. 1 byte should contain 1 DATA PIXEL, the other BYTE should contain other PIXEL value in whole 16 bits and so on so forth.

7条回答
Anthone
2楼-- · 2019-01-22 04:14

It can be done like this:

mask = ~(~0 << (end - start + 1));
value = (n >> start) & mask;

where n is the original integer and value is the extracted bits.

The mask is constructed like this:

1. ~0 = 1111 1111 1111 1111 1111 1111 1111 1111
2. ~0 << (end - start + 1) = 1111 1111 1111 1111 1100 0000 0000 0000
   // assuming we are extracting 14 bits, the +1 is added for inclusive selection
   // ensure that end >= start
3. ~(~0 << (end - start + 1)) = 0000 0000 0000 0000 0011 1111 1111 1111

Now n is shifted right by start bits to align the desired bits to the left. Then a bitwise AND gives the result.

查看更多
登录 后发表回答