Reputation: 1147
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
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