QByteArray is an integer

As you can tell from the name, I am 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. buffer does not receive any ASCII character, and I believe that the toInt() function will not work if it is not an ASCII character. int size should be 37 (0x25), but, as I said, this is 0.

q_size is 0x2500 (or another order order is 0x0025 ).

What is the problem? I am sure q_size contains the data I need.

+6
qt bytearray
source share
8 answers

I have not tried this myself to see if it works, but it looks from Qt docs how you want a QDataStream. This supports the extraction of all the basic C ++ types and can be created using QByteArray as input.

+8
source share

Something like this should work using the 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 
+18
source share

toInt method parses an int if the QByteArray contains a string with numbers. You want to interpret the source bits as a whole. I don’t think there is a way to do this in QByteArray , so you will need to build the value yourself from the bytes of the songs. Perhaps 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 vice versa, depending on Endianness)

+5
source share

I had big problems converting serial data (QByteArray) to an integer, which was intended to be used as a value for the 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.. 
+1
source share

This works for me:

 QByteArray array2; array2.reserve(4); array2[0] = data[1]; array2[1] = data[2]; array2[2] = data[3]; array2[3] = data[4]; memcpy(&blockSize, array2, sizeof(int)); 

data is qbytearray, from index = 1 to 4 is an integer.

0
source share

Create a QDataStream that works with your QByteArray. Documentation here

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

works for me

0
source share

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

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

0
source share

All Articles