gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:20:26 25 4
gpt4 key购买 nike

简短:我想按顺序将数据逐字节写入文件。使用 file.write 将数据传输到文件。但是当我用 hexdump 查看文件时,写入的数据不按顺序。

这是我的代码:

#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;
}

当我在输出上使用 hexdump 时,它会显示:

0201 0403 0304 0102

字节已重新排列。

我希望输出是:

0102 0304 0403 0201

为什么会发生重新排列?

我怎样才能实现字节顺序传输?

最佳答案

hexdump 转储 2 个字节的单词;不是单个字符。这就是让你感到困惑的地方 - 试试

od -t x1

关于c++ - 为什么 file.write() 不按照我给出的顺序存储字节? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40650658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com