Converting a QByteArray in Hexa format into an Int
-
@Pantoufle
Hi. I don't understand if you still have a problem or a question? You want a 4 byte integer, and you have one. I don't understand what the relevance is of a string you choose to pass toQByteArray::fromHex()
as a convenient way of getting the 4 bytes into memory, who cares what the string is or how long it is? It has nothing to do with how your device works, which does not use hex or strings, it just sends a 4-byte integer.Which should be convertible viaQByteArray::toInt()
provided the byte order matches your machine's endian order (else it would need swapping).My bad, see @Christian-Ehrlicher's clarification of
QByteArray::toInt()
below!@JonB said in Converting a QByteArray in Hexa format into an Int:
Which should be convertible via QByteArray::toInt() provided the byte order matches your machine's endian order (else it would need swapping).
No, you're wrong here.
QByteArray::toInt() converts a string representation of a number to an integer.int32_t val = *(reinterpret_cast<int32_t*>(ba.constData()))
if the endian is the same on the source and destination, otherwise use the qEndian helper functions.
-
@JonB said in Converting a QByteArray in Hexa format into an Int:
Which should be convertible via QByteArray::toInt() provided the byte order matches your machine's endian order (else it would need swapping).
No, you're wrong here.
QByteArray::toInt() converts a string representation of a number to an integer.int32_t val = *(reinterpret_cast<int32_t*>(ba.constData()))
if the endian is the same on the source and destination, otherwise use the qEndian helper functions.
@Christian-Ehrlicher
Oh, I am so wrong, I should have looked atQByteArray::toInt()
docs before answering instead of assuming it was a binary operation! I now understand where the confusion lies totally! I will cross out my earlier. -
@JonB said in Converting a QByteArray in Hexa format into an Int:
Which should be convertible via QByteArray::toInt() provided the byte order matches your machine's endian order (else it would need swapping).
No, you're wrong here.
QByteArray::toInt() converts a string representation of a number to an integer.int32_t val = *(reinterpret_cast<int32_t*>(ba.constData()))
if the endian is the same on the source and destination, otherwise use the qEndian helper functions.
Just use the Qt endian functions every time, since they evaluate to a no-op (ie
static_cast
) when the source and destination match anyway. Eg:const QByteArray mydata = QByteArray::fromHex("00004A9E"); const quint32 mydataInteger = qFromBigEndian<quint32>(mydata); qDebug() << mydata; qDebug() << mydataInteger;
Outputs:
"\x00\x00J\x9E" 19102
Cheers.