我正在使用字节寻址数组ParameterArray [20],它有多个不同长度的连续参数:
ParameterA: Start = 0; Length = 2
ParameterB: Start = 2; Length = 1
ParameterC: Start = 3; Length = 6
...
我想建立一个像这样的函数:
int ExtractedData(startBit, endBit, ParameterStart)
{
return (ParameterArray[ParameterStart] >> endBit) && 2^startBit;
}
如果我超过8位,或者例如如果我想要多字节参数的中间位(即参数C的位17:5),则上述情况不会起作用
有关如何实施此建议的任何建议?
编辑:我已经修改了我的函数,但是我仍然受到这个实现的int大小的限制:
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);
}
答案 0 :(得分:1)
我认为有两个错误。变化:
return (ParameterArray[ParameterStart] >> endBit) && 2^startBit;
为:
return (ParameterArray[ParameterStart] >> endBit) & ((1 << (endBit - startBit)) - 1);
^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
need bitwise AND here (not logical AND) -------- need a suitable mask here
请注意^
是C和相关语言中的按位XOR运算符,它不是取幂运算符。