Search code examples
c++qthexqbytearray

Reading & Interpreting Binary file in Qt


Trying to read a binary file in Qt.

The file has mixed text and binary (hex) data.

THe file contains regions of data with the lengths specified by hex numbers.

For example:

00 01 BE 00 00 00 00 00 00 00 00 00 01

Here "BE" is at offset BB in the file. BE is 190, so I scroll forward to the last byte above and I know the next 190 bytes are my data.

I've been struggling for a couple of days trying to get my Qt code convert the Byte value "BE" as above to the number 190.

The best I get is "-66", which is of course 190-256.

Another example is:

00 01 D3 63 00 00 00 00 00 00 00 01

Should be converted to "63D3" which is 25555 decimal.

Here are my code snippets:

  1. Read the file:

    QFile file(iFile);
    if (!file.open(QIODevice::ReadOnly)) return;
    QByteArray iContents = file.readAll();
    
  2. Get the length

    ushort  c3 = 0xFF;
    c3 = iContents.at(2); // c3 should be "BE" hex.
    printf ( "%0x %d\n", c3, c3 );
    

Output is :

FFFFFFBE -66

How do I get this is be read as 190?

I've tried various things after searching but nothing seems to work which suggest I am missing something basic in my code.

Current code to do the conversion is:decimal


Solution

  • QByteArray::at() returns a (signed) char and you assign it to an unsigned short. You want the value 0xbe to be treated as unsigned, so you should cast it : c3 = (unsigned char) iContents.at(2);

    For the 2 bytes little-endian integer (I assume it's just D363 you are interested in and the zeros are meaningless here ?):

    unsigned short i = (unsigned char) iContent.at(2) | (unsigned char) iContent.at(3) << 8;

    The (unsigned char) cast has highest precedence, and the operands of bitwise operators are promoted to integers (this is why the shift result isn't zero).