unsigned short
可能是也可能不是 2 个字节。让我们看看您的示例的内存。
+---+---+---+ +---+---+---+
| | | | ... | | | |
+---+---+---+ +---+---+---+
|<-------- len bytes -------->|
如果unsigned short
是 2 个字节长,则您有空间len/2
unsigned short
值。或者,更一般地说,您有len/n
unsigned short
值的空间,其中n
等于sizeof(unsigned short)
。
你不能投一个unsigned char *
tounsigned char *
并期望事情可以便携。现在,要计算peak
,这取决于您要执行的操作。如果您想找到最大值len
unsigned char
并将其保存到peak
中,则循环这些值将起作用:
size_t i;
unsigned short peak = 0;
for (i=0; i < len; ++i) {
if (buffer[i] > peak) {
peak = buffer[i];
}
}
但是,如果您想将值“组合”sizeof(unsigned short)
成一个unsigned short
值,那么最好的办法是手动计算数字。
假设它len
可以被 , 和大端存储整除n
,您可以执行以下操作(未经测试):
#include <stdio.h>
#include <limits.h>
size_t factor = sizeof(unsigned short);
size_t n = len / factor;
size_t i;
unsigned short peak = 0;
if (len % factor != 0) {
fprintf(stderr, "Extra data at the end\n");
}
for (i=0; i < n; ++i) {
size_t j;
unsigned short test = 0;
for (j=0; j < factor; ++j) {
test = (test << CHAR_BIT) + buffer[i*factor+j];
}
if (test > peak) {
peak = test;
}
}