[solved]Writing hex string to file
-
I am trying to read a file containing binary data, and write it out to another file in ascii format.
I want to display a string representing a single hex byte in the output file, e.g. 76 = "4C".I am getting formatting/padding characters in my output file when I use the following code :-
@
QFile binaryFile("binaryData.sim");
QFile asciiFile("C:\Temp\BinaryToAscii.txt");
if (!binaryFile.open(QIODevice::ReadOnly))
return;
if (!asciiFile.open(QIODevice::ReadWrite | QIODevice::Text))
return;asciiFile.flush(); int size = binaryFile.size(); QDataStream in(&binaryFile); // read the data serialized from the file QDataStream out(&asciiFile); // output file for (int i=0; i<size; i++) { quint8 byteRead; in >> byteRead; // extract a byte QString hex; hex.setNum(byteRead, 16); std::string hexString = hex.toStdString(); QString hexQString(hexString.c_str()); std::cout << std::hex << hexString; out << "hex = "; out << std::hex << hex; out << "hexQString = "; out << std::hex << hexQString; }
@
The statement
@ std::cout << std::hex << hexString;
@successfully displays the hex string on the standard output area, without any apparent additional formatting etc.
Both "hex" and "hexQString" appear with the blank rectangles formatting/padding.
How can I write the hex data to the ascii file without the accompanying formatting/padding characters?
-
I should expand on that for clarification...
My problem is with writing to the file.
I have verified on line 23 that the hex value is OK when displayed on std::cout@std::cout << std::hex << hexString;@
My problem arises when I try to write that string to the file.
I haven't much experience of file I/O, so I suspect I'm missing something.
Am I opening the file correctly?
Amy I using the right commands to try to write a string to the file? -
Why don't you use something like this (untested code!):
@
QFile binaryFile("binaryData.sim");
QFile asciiFile("C:\Temp\BinaryToAscii.txt");
if (!binaryFile.open(QIODevice::ReadOnly))
return;
if (!asciiFile.open(QIODevice::ReadWrite | QIODevice::Text))
return;QByteArray input;
do {
input = binaryFile.read(1024);
asciiFile.write(input.toHex());
} while (input.size() == 1024);
@That way you do not have to do all the useless byte to QChar conversions you are currently doing and you read chunks of 1024 bytes instead of one byte at a time.