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.
There are two building blocks that you need to know to build this yourself:
N
least significant bits requires constructing a bit mask withN
ones at the end. You do it like this:((1 << N)-1)
.1 << N
is2 ^ N
: it has a single1
at theN+1
st position, and all zeros after it. Subtracting one gives you the mask that you need.M
least significant bits is a simple shift to the right:k >> M
Now your algorithm for cutting out from
M
toN
becomes a two-step process: you shift the original valueM
bits to the right, and then perform a bit-wiseAND
with the mask ofN-M
ones.This fragment cuts out bits from 4, inclusive, to 16, exclusive, and prints
bee
when you run it. Bits are numbered from zero.Although its a very old question, I would like to add a different solution. Using macros,
/* Here, startBit : start bit position(count from LSB) endBit : end bit position(count from LSB) .NOTE: endBit>startBit number : the number from which to extract bits maxLength:the total bit size of number. */ `
`
Output : Inputs : 1 5 255 32
Input number : 255
Output : 62
Here, 255 = 11111111 and 62 = 00111110
you can add parameters to get the values out or something
Note that
[begin, end)
is a half open interval.