私はあなたのコードからあなたがネットワークから読んでいると推測できます。これは、バッファからint
を読み取るだけでは移植できません。ネットワークプロトコルでエンディアンを選択しましたが、プログラムが実行されるすべてのプラットフォームが同じであると予想できないため、変換が正しく行われません。 read
にint
を返すように提案する他の提案された解決策でも、同じ問題が発生します。
あなたのケースでは、配列を繰り返し処理し、プラットフォームのエンディアンに応じてバイトを正しい場所に配置することによって整数を計算するというアドバイスしかできません。
GCCのマクロ__BYTE_ORDER__
を使用すると、ビルドターゲットプラットフォームのエンディアンを検出できます。
ビッグエンディアンであるネットワークデータの例があります:
// construct an `int` with the bytes in the given buffer
// considering the buffer contains the representation
// of an int in big endian
int buffer_to_int(char* buffer, int buffer_size) {
int result = 0;
int i;
char sign = buffer[0] & 0x80;
char * res_bytes = (char*)&result; // this pointer allows to access the int bytes
int offset = sizeof(int) - buffer_size;
if(sign != 0)
sign = 0xFF;
if(offset < 0) {
// not representable with a `int` type
// we chose here to return the closest representable value
if(sign == 0) { //positive
return INT_MAX;
} else {
return INT_MIN;
}
}
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
for(i=0; i<buffer_size; i++) {
res_bytes[i] = buffer[buffer_size-i-1]; // invert the bytes
}
for(i=0; i<offset; i++){
res_bytes[buffer_size+i] = sign;
}
#else
// same endianness, so simply copy bytes using memcpy
memcpy(&result + offset, buffer, buffer_size);
for(i=0; i<offset; i++){
res_bytes[i] = sign;
}
#endif
return result;
}
あなたはint型に直接読むことができたが。 – tkausl
また、 'char buffer [sizeof(int)]'と 'int value'メンバで' union'を定義してください。ファイルを 'buffer'にロードし、次にint値' value'を使います。 – i486
https://linux.die.net/man/3/htons - ネットワーク上で通信するために、このファンクションファミリを使用してください。 –