Im trying to read a byte file with fstream in c++ (goal: binary data format deserialization). The dat file looks something like below in HxD Hex editor (bytes.dat):
but something goes wrong when reading the binary file into a char array.. here is a mwe:
#include <iostream>
#include <fstream>
using namespace std;
int main (){
ofstream outfile;
outfile.open("bytes.dat", std::ios::binary);
outfile << hex << (char) 0x77 << (char) 0x77 << (char) 0x77 << (char) 0x07 \
<< (char) 0x9C << (char) 0x04 << (char) 0x00 << (char) 0x00 << (char) 0x41 \
<< (char) 0x49 << (char) 0x44 << (char) 0x30 << (char) 0x00 << (char) 0x00 \
<< (char) 0x04 << (char) 0x9C;
ifstream infile;
infile.open("bytes.dat", ios::in | ios::binary);
char bytes[16];
for (int i = 0; i < 16; ++i)
{
infile.read(&bytes[i], 1);
printf("%02X ", bytes[i]);
}
}
but this shows in the cout (mingw compiled):
> g++ bytes.cpp -o bytes.exe
> bytes.exe
6A 58 2E 76 FFFFFF9E 6A 2E 76 FFFFFFB0 1E 40 00 6C FFFFFFFF 28 00
im doing something wrong. How is it possible that there 4 bytes in some of the array entries?
bytes
as anunsigned char
array or castbytes[i]
tounsigned char
. – Captain Obvliousoutfile.write()
instead of theoperator<<
to store binary data. – πάντα ῥεῖ