unsigned short
可能是也可能不是2個字節。讓我們看看你的例子的內存。
+---+---+---+ +---+---+---+
| | | | ... | | | |
+---+---+---+ +---+---+---+
|<-------- len bytes -------->|
如果unsigned short
爲2個字節長,你有len/2
unsigned short
值空間的價值。或者,更一般地說,您有len/n
unsigned short
值的空間,其中n
等於sizeof(unsigned short)
。
你不能投unsigned char *
到unsigned 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;
}
}