QByteArray to integer

As you may have figured out from the title, I'm having problems converting a QByteArray to an integer.

 QByteArray buffer = server->read(8192);
 QByteArray q_size = buffer.mid(0, 2);
 int size = q_size.toInt();

However, size is 0. The buffer doesn't receive any ASCII character and I believe the toInt() function won't work if it's not an ASCII character. The int size should be 37 (0x25), but - as I have said - it's 0.

The q_size is 0x2500 (or the other endianness order - 0x0025).

What's the problem here ? I'm pretty sure q_size holds the data I need.


I haven't tried this myself to see if it works but it looks from the Qt docs like you want a QDataStream. This supports extracting all the basic C++ types and can be created wth a QByteArray as input.

Something like this should work, using a data stream to read from the buffer:

QDataStream ds(buffer);
short size; // Since the size you're trying to read appears to be 2 bytes
ds >> size;

// You can continue reading more data from the stream here

The toInt method parses a int if the QByteArray contains a string with digits. You want to interpret the raw bits as an integer. I don't think there is a method for that in QByteArray, so you'll have to construct the value yourself from the single bytes. Probably something like this will work:

int size = (static_cast<unsigned int>(q_size[0]) & 0xFF) << 8
         + (static_cast<unsigned int>(q_size[1]) & 0xFF);

(Or the other way around, depending on Endianness)

bool ok;
q_size.toHex().toInt(&ok, 16);

works for me

I had great problems in converting serial data (QByteArray) to integer which was meant to be used as the value for a Progress Bar, but solved it in a very simple way:

QByteArray data = serial->readall();
QString data2 = tr(data); //converted the byte array to a string
ui->QProgressBar->setValue(data2.toUInt()); //converted the string to an unmarked integer..

This works for me:

QByteArray array2;
        array2[0] = data[1];
        array2[1] = data[2];
        array2[2] = data[3];
        array2[3] = data[4];

        memcpy(&blockSize, array2, sizeof(int));

data is a qbytearray, from index = 1 to 4 are array integer.

Create a QDataStream that operates on your QByteArray. Documentation is here

Try toInt(bool *ok = Q_NULLPTR, int base = 10) const method of QByteArray Class.

QByteArray Documentatio: http://doc.qt.io/qt-5/QByteArray.html

Need Your Help

Perl build, unit testing, code coverage: A complete working example

perl unit-testing build-process build-automation code-coverage

Most Stackoverflow answers that I have found in regards to the Perl build process and unit testing and code coverage simply point me to CPAN for the documentation there. There's absolutely nothing...

What exactly are Delay signing and strong names in .net?

c# .net delay-sign

I have seen in many article it is written that