spizzak
spizzak

Reputation: 1147

Extract Specific Bits from Array in C

I'm working with a byte-addressed array ParameterArray[20] which has multiple contiguous parameters of varying length:

ParameterA: Start = 0; Length = 2
ParameterB: Start = 2; Length = 1
ParameterC: Start = 3; Length = 6
...

I would like to build a function like so:

int ExtractedData(startBit, endBit, ParameterStart)
{
    return (ParameterArray[ParameterStart] >> endBit) && 2^startBit;
}

The above however wont work if I exceed 8bits, or for example if I want the middle bits of a multi-byte parameter (ie. bits 17:5 of Parameter C)

Any suggestions on how to implement this?

Edit: I've modified my function as follows but I'm still limited by the size of int with this implementation:

int ExtractedData(startBit, endBit, ParameterStart, parameterLength)
{
    int tempVar = 0;

    for (int i=0; i < parameterLength; i++)  {
         tempVar = (tempVar << 8 | ParameterArray[ParameterStart+ i]; 
    }    
    return (tempVar >> endBit) & ((1 << (startBit - endBit + 1)) - 1);
}

Upvotes: 1

Views: 1323

Answers (1)

Paul R
Paul R

Reputation: 212949

Two mistakes, I think. Change:

return (ParameterArray[ParameterStart] >> endBit) && 2^startBit;

to:

return (ParameterArray[ParameterStart] >> endBit) & ((1 << (endBit - startBit)) - 1);
                                                  ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                                                  |                |
   need bitwise AND here (not logical AND) --------      need a suitable mask here

Note that ^ is the bitwise XOR operator in C and related languages, it is not an exponentiation operator.

Upvotes: 1

Related Questions