Problem Displaying QByteArray Binary String as Hex String in qDebug
I want to debug my QByteArray of binary values, but it is much easier to read the binary value as a Hex string.
Here's a simplified example of the code:
qint32 offset = 0; // For cases when inserting values at non-word split (i.e. bit 13)
qint32 value = 65494; // Hex value is FFD6
binValue.insert(offset, QString::number(value, 2));
// Display value as Hex string
qDebug() << binValue.data(); // shows "1111111111010110"
qDebug() << binValue.toHex().data(); // shows "3131313131313131313130313031..."
qDebug() << QString(binValue.data()); // shows "1111111111010110"
qDebug() << QString::number(QString(binValue.data()).toInt(&ok, 16)); // shows "0"
qDebug() << QString::number(QString(binValue.data()).toInt(&ok, 16), 16); // shows "0"@
How can I display the binary string as a Hex string, "FFD6"?
What you need is writing a function by yourself ;-)
QByteArray bin2Hex(const QByteArray& input)
Oh dear, another person confused by the difference between a number and its representation as a string. Your binValue QByteArray contains a string of 16 characters (bytes) that read to a human as the binary representation of the number. Converting those 16 bytes to 32 hexadecimal characters (your line 10) is nothing like the same thing as displaying the original number in hex. Converting those 16 characters to a number by treating it as if it were a hexadecimal representation (your lines 12/13) will not give you the original number and, in general will overflow an int... ok == false and return is 0.
If you want value converted to a hex string then just ask for it that way:
int value = 65494; // the original number (it is in binary in memory)
qDebug() << QString::number(value, 16); // displayed as a hex string
// Converting a hex string back to a number
int value = QString("FFD6").toInt(&ok ,16);
qDebug() << value << ok;