为什么 file.write() 不按照我给出的顺序存储字节?C++
Why doesn't file.write() store bytes in the sequence I have given ? c++
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
相关文章:
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 当比特(而不是字节)的顺序至关重要时的持久性
- 如何使用连接器 c++ 在 mySQL 表二进制(16) 字段中存储 c++ 字节数组?
- 将字符指针按顺序存储在 map 中 std::map<char*, int> mymap。将其存储为字符或字符串不是一个选项
- 以相反顺序存储整数值
- C++以相反的顺序存储字符串
- 将网络字节顺序(大字节序)转换为小字节序
- 在 c++ 中存储字节模式
- C++:了解我的计算机如何存储字节
- 如何使用节俭C++ API 在 HBase 中存储字节数组(突变结构中的值是文本 ..)
- STL 按排序顺序存储数字
- 数组是否以相反的顺序存储在 C/C++中
- 为什么 libstdc++ 以相反的顺序存储 std::tuple 元素
- 按顺序存储不同类型的对象
- 编译lua代码,存储字节码,然后加载并执行它
- 为什么 file.write() 不按照我给出的顺序存储字节?C++
- 如何在c++中按列主顺序存储二维数组中的值
- 如何在Vector中按字母顺序存储字符串
- 网络字节顺序和字节序问题
- 用于按排序顺序存储元素并允许快速索引的数据结构