2

QDataStreama で書かれたバイナリ ファイルを aで、LittleEndian でエンコードしたものを読みたいstd::fstream(同じプラットフォーム上で、異なる形式を持つ 1 つのデータ型の問題は問題ではありません)。

これを行うにはどうすればよいですか?私の知る限り、std::fstreamLittleEndian データを読み書きする機能が組み込まれていません。

問題を掘り下げたところ、次のことがわかりました(疑似コード):

ofstream out;      //initialized to file1, ready to read/write
ifstream in;       //initialized to file2; ready to read/write
QDataStream q_out; //initialized to file2; ready to read/write

int a=5, b;
//write to file1
out << a; //stored as 0x 35 00 00 00. Curiously, 0x35 is the character '5' in ASCII-code
//write to file2
q_out << a; //stored as 0x 05 00 00 00

//read from file2 the value that was written by q_out
in >> b; //will NOT give the correct result

//read as raw data
char *c = new char[4];
in.read(c, 4);

unsigned char *dst = (unsigned char *)&b;
dst[3] = c[3];
dst[2] = c[2];
dst[1] = c[1];
dst[0] = c[0];
//b==5 now

要約するとQDataStream、 とは異なる形式でバイナリ データを書き込みますstd::fstreamQDataStreamを使用して書き込まれたバイナリ データを読み取る簡単な方法はありstd::fstreamますか?

4

1 に答える 1

2

リトル エンディアン マシンを使用していると仮定すると、次の int を含むファイルを読み取る可能性が非常に高くなります。

05 00 00 00

次のように簡単です。

int32_t x;
in.read((char*)&x, sizeof(int32_t));
assert(x == 5);

さらにいくつかのメモ:

  • 演算子>><<フォーマットされた i/o を実行します。つまり、値をテキスト表現に変換したり、テキスト表現から変換したりしますが、これはケースとは関係ありません。
  • ファイルはバイナリ モード (ios_base::binaryフラグ) で開く必要があります。POSIX はバイナリとテキストを区別しませんが、他の一部の OS は区別します。
于 2013-02-07T09:57:15.490 に答える