user3155501 user3155501 - 4 months ago 18
C++ Question

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

I want to write data byte for byte in sequence to a file.
The data is transfered to the file with file.write.
But when I review the file with hexdump the written data is not in sequence.

Here is my code:

#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;"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) );

return 0;

When I use hexdump on the output it displays this:

0201 0403 0304 0102

The bytes have been rearranged.

I expect the output to be:

0102 0304 0403 0201

Why is the rearranging happening ?

And how can I achieve a transfer where the bytes are in sequence ?


The hexdump dumps 2-bytes words; not individual characters. That is what is confusing you - try

od -t x1