1

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);
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I fixed those two errors you mention but do you have any suggestions on how to expand this to work with multi-byte parameters?
What is the maximum width in bits that you need to return ? E.g. would it always fit in a 32 bit int ?
I've made the modification in order for it to be able to handle up to a 32 bit int but I'm not sure how efficient it is. I also need to return up to 6 bytes sometimes but ultimately I could work around that issue if there is no better way to deal with it.
Well if you need up to 6 bytes then use a suitable 8 byte data type, such as uint64_t.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.