c:将给定序列的字节解释为 int16_t 值并将它们相加

c: interpreting bytes of a given sequence as int16_t values and summing them

我想弄清楚如何将从给定位置 (sequenceOffset) 开始的数据块中的顺序字节添加到特定长度 (sequenceLength),方法是将它们打字为带符号的 16 位整数 (int16_t).数字可以是负数,positive.I 也不能使用任何数组,只能使用指针语法。

*blockAddress points to the first byte of the memory region
*blockLength is number of bytes in the memory region
* sequenceOffset is the offset of the first byte of the sequence that
* is to be summed
* sequenceLength is the number of bytes in the sequence, and
* sequenceLength > 0
*
* Returns: the sum of the int16_t values obtained from the given sequence;
* if the sequence contains an odd number of bytes, the final byte
* is ignored; return zero if there are no bytes to sum


int16_t sumSequence16(const uint8_t* const blockAddress, uint32_t blockLength,
uint32_t sequenceOffset, uint8_t sequenceLength){

uint16_t sum = 0; 
const uint8_t* curr = blockAddress; // deref
uint16_t pointer  = *(uint16_t*)curr; // typecast to int16

 for (uint16_t i = 0; i< sequenceLength; i++){
     sum = sequenceOffset  + (pointer +i +1);
 }// for

测试用例示例:

--偏移量113处8个字节的求和序列:

5D 5C 4E 6E FA B3 5D 4C

23645 28238 -19462 19549

你说的总和是:-7412

应该是:-13566

如果序列包含奇数个字节,我不确定如何处理忽略最后一个字节的情况。

#include <stdint.h>
#include <stdio.h>

int16_t sumSequence16sane(const uint8_t* block, uint32_t length)
{
    int16_t ret = 0;
    while (length >= 2)
    {
       ret += block[1] << 8 | block[0];
       block += 2;
       length -= 2;
    }
    return ret;
}

int16_t sumSequence16(const uint8_t* const blockAddress, uint32_t blockLength,
uint32_t sequenceOffset, uint8_t sequenceLength)
{
    return sumSequence16sane (blockAddress + sequenceOffset, sequenceLength);
}

int main()
{
    uint8_t b[8] = { 0x5d, 0x5c, 0x4e, 0x6e, 0xfa, 0xb3, 0x5d, 0x4c };
    printf("%d\n", sumSequence16sane(b, 8));
}

有些人可能更喜欢这个内部循环。它更紧凑但可能更令人困惑:

    for (; length >= 2; block += 2, length -= 2)
       ret += block[1] << 8 | block[0];