I am trying to write a binary document. So far, I succeeded in writing a .bin where the content has an hexadecimal format. I would like to have the content in a binary format (0 and 1 only).
Is it possible ? How to do it ? Am I wrong in my idea and having it in hexadecimal or binary is the same thing ?
Here is my code so far :)
#include <QApplication>
#include <QDataStream>
#include <QString>
#include <QFile>
#include <iostream>
#include <QDebug>
#include <QTextStream>
void createBinaryFile()
{
int a = 22;
QFile file("/home/.../facts.bin");
if (!file.open(QIODevice::WriteOnly)) {
std::cerr << "Cannot open file for writing: "
<< qPrintable(file.errorString()) << std::endl;
return;
}
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_3);
out << quint32(0x12345678) << a;
QTextStream writeInConsole(stdout);
writeInConsole << a;
file.flush();
file.close();
}
void readBinaryFile()
{
quint32 n;
int a;
QFile file("/home/.../facts.bin");
if (!file.open(QIODevice::ReadOnly)) {
std::cerr << "Cannot open file for reading: "
<< qPrintable(file.errorString()) << std::endl;
return;
}
QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_3);
in >> n >> a;
QTextStream okk(stdout);
okk << a;
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
createBinaryFile();
//readBinaryFile();
return app.exec();
}
And this is the content of facts.bin : 1234 5678 0000 0016
Thank you very much for your help ! :)
operator<<). By definition, they format numbers into readable values. And you don't want aQDataStream- as its documentation says, it's a platform-independent transfer representation. You probably want towriteRawData()or simply use yourQIODevicedirectly (i.e.QIODevice::write()).