为什么 file.write() 不按照我给出的顺序存储字节?C++

Why doesn't file.write() store bytes in the sequence I have given ? c++

本文关键字:顺序存储 字节 C++ write file 为什么      更新时间:2023-10-16

Short:我想按顺序将数据字节逐个字节写入文件。数据通过 file.write 传输到文件。但是当我使用十六进制转储查看文件时,写入的数据不是按顺序排列的。

这是我的代码:

#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

为什么会发生重新排列?

我怎样才能实现字节按顺序排列的传输?

十六进制转储转储 2 个字节的单词;而不是单个字符。这就是让您感到困惑的地方 - 尝试

od -t x1