tags:

views:

751

answers:

3

As you may have figured out from the title, I'm having problems converting 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 endianess order - 0x0025).

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

Please help :)

Thanks !

+1  A: 

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 songle 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)

sth
There's no simpler way ? It would require quite some work if I'd do this not only for WORDs, but for DWORDs, QWORDs, floats, and so on ...
Ahmed
+3  A: 

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.

Troubadour
+1  A: 

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
Ropez
Hmm, sounds familiar :)
Troubadour
I already gave your answer a +1. Just wanted to add an example.
Ropez