2016-11-17 7 views
1

短く: ファイルに順番にバイトのデータを書きたいと思います。 データはfile.writeでファイルに転送されます。 しかし、ファイルをhexdumpで見直すと、書き込まれたデータは順不同です。私は出力にhexdumpに対してを使用する場合file.write()は、指定したシーケンスにバイトを格納しないのはなぜですか? C++

#include <iostream> 
#include <fstream> 
#include <stdint.h> 

int main() { 
    // array with four bytes I want to write 
    // This should be 0x01020304 in memory 
    char write_arr[4]={1,2,3,4}; 

    // int with four bytes I want to write 
    // I use little endian so this should be 0x04030201 in memory 
    int write_num=0x01020304; 

    std::ofstream outfile; 

    outfile.open("output.txt",std::ios::out | std::ios::binary | std::ios::trunc); 

    if(outfile.is_open()) { 
     outfile.write(write_arr ,sizeof(write_arr)/sizeof(char)); 
     outfile.write(reinterpret_cast<char *>(&write_num),sizeof(write_num)); 
     outfile.close(); 
    } 

    return 0; 
} 

が、それは、この表示されます:バイトが再配置されている

0201 0403 0304 0102 

は、ここに私のコードです。

私は、出力があることを期待:

0102 0304 0403 0201 

はなぜ並べ替えが起こっているのでしょうか?

バイトを順番に転送するにはどうすればよいですか?

+1

どうやってヘキサダンプをやっていますか?単語ではなくバイトをダンプする必要があります。 –

+0

charでダンプする 'od -t x1'。 –

答えて

1

hexdumpは2バイトワードをダンプします。個々の文字ではありません。 これはあなたを混乱させるものです - 試してみてください

od -t x1 
+0

それが解決しました。ありがとう! – user3155501

関連する問題