[Solved] Print qint as QString without losing bits
-
@
qint32 my32=1; //dec
qint16 my16=0x0002; //hex
qint8 my8=0x03; //hexcout << QString::number(my32).toStdString <<"\n";
cout << QString::number(my16).toStdString <<"\n";
cout << QString::number(my8).toStdString <<"\n";
@cout will print:
"1"
"2"
"3"I would like it to print the complete data type size like:
"00000001"
"0002"
"03"The reason is that I have to stick to a protocol that requires that a 32 bit integer shall be represented with a string of 8 chars like "00000000".
In my code the data is represented with the correct type. however when the data is transformed into a datagram package i have to pad it to fill out the expected data type width.
for example a datagram message looks like:@
struct datagramHeader
{
qint32 segment; //s
qint16 class; //c
qint16 length; //l
}when converted to an datagram it needs to look like this:
"ssssssssccccllll"
@I find it convenient to work with the data types as they are like qint for counters etc and cast them to a QString when the datagram message is created. I guess this must be the best way and to solution is to handle the conversion from qint to QString without losing any characters. Or am I wrong?
-
Hi,
Unless I've misunderstood you you could use something like:
@
datagramHeader header = { 1, 0x02, 0x03 };
QString datagram("%1%2%3");
qDebug() << message.arg(header.segment, 8, 10, QChar('0'))
.arg(header.class, 4, 16, QChar('0'))
.arg(header.length, 4, 16, QChar('0'));
@Hope it helps
-
You could fix your code like that (fill with leading zeros):
@
QString::number(my32).rightJustified(8, '0');
@But I guess your protocol requires hex output? (the value 0xFFFFFFFF represented as decimal would not fit into 8 characters). If so you should also add the formatting base:
@
int base = 16;
int width = sizeof(my32)*2;
QString::number(my32, base).rightJustified(width, '0');
@ -
It actually works. I used the .rightJustified method and that in combination with changing all my qint to quint solved all my issues.
Thanks to SGaist and flandi for your help in this topic!