以下のコードは、C (Arduino) の 8 ビットのバイト配列を 16 ビットの int 配列に変換することになっていますが、部分的にしか機能していないようです。何が間違っているのかわかりません。
バイト配列はリトル エンディアンのバイト順です。int (エンティティごとに 2 バイト) 配列に変換するにはどうすればよいですか?
簡単に言えば、2バイトごとにマージしたいのです。
現在、次の入力 BYTE ARRAY を出力しています{0x10, 0x00, 0x00, 0x00, 0x30, 0x00}
。出力 INT ARRAY は次のとおり{1,0,0}
です。出力は INT ARRAY is: である必要があります{1,0,3}
。
以下のコードは、私が現在持っているものです。
Stack Overflow question Convert bytes in a C array as longsの解決策に基づいてこの関数を作成しました。
また、バイト配列から長い(32ビット)配列まで正常に機能する同じコードに基づいたこのソリューションもありますhttp://pastebin.com/TQzyTU2j
。
/**
* Convert the retrieved bytes into a set of 16 bit ints
**/
int * byteA2IntA(byte * byte_slice, int sizeOfB, int * ret_array){
//Variable that stores the addressed int to be stored in SRAM
int currentInt;
int sizeOfI = sizeOfB / 2;
if(sizeOfB % 2 != 0) ++sizeOfI;
for(int i = 0; i < sizeOfB; i+=2){
currentInt = 0;
if(byte_slice[i]=='\0') {
break;
}
if(i + 1 < sizeOfB)
currentInt = (currentInt << 8) + byte_slice[i+1];
currentInt = (currentInt << 8) + byte_slice[i+0];
*ret_array = currentInt;
ret_array++;
}
//Pointer to the return array in the parent scope.
return ret_array;
}