问题
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.
回答1:
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.
回答2:
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
回答3:
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)
回答4:
bool ok;
q_size.toHex().toInt(&ok, 16);
works for me
回答5:
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..
回答6:
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 a qbytearray, from index = 1 to 4 are array integer.
回答7:
Create a QDataStream that operates on your QByteArray. Documentation is here
回答8:
Try toInt(bool *ok = Q_NULLPTR, int base = 10) const
method of QByteArray Class.
QByteArray Documentatio: http://doc.qt.io/qt-5/QByteArray.html
来源:https://stackoverflow.com/questions/1251662/qbytearray-to-integer