rbaleksandar
rbaleksandar

Reputation: 9681

Adding padded number as QString to QByteArray produces unwanted character

I have a QByteArray which contains the telegram in a special format that is then sent via UDP to a remote machine for further processing. I use QByteArray::append() to put the telegram together.

One of the components of the telegram is an index: 1, 2, 3, ..., 999. This index needs to be padded with zeroes in the front: 001, 002, 003, ..., 999. In order to do that I initially hard coded the index for testing purposes:

...
telegram.append("001");
...

but later I obviously had to move to a more general solution like

...
QString paddedIdx = QString("%1").arg(idx, 2, QChar('0'));
telegram.append(paddedIdx);
...

The initial try worked without any issues. Looking in the debugged contents of the telegram I was able to see that "002" is appended to the byte array. However with the new solution I get "0\002" and as a result the processing of the telegram on the remote machine fails (I use reg ex for the parsing). If I'm not mistaken the \0 is the terminating character however it's definitely something I'm not expecting to see in my byte array.

Upvotes: 0

Views: 933

Answers (2)

Murphy
Murphy

Reputation: 3999

The reason for your problem is that your call of arg() is missing the base parameter. So instead of calling

QString::arg(int a, int fieldWidth, int base, const QChar& fillChar)

the compiler selects a matching overload, does an implicit cast to an (unprintable) char and calls

QString::arg(QChar a, int fieldWidth, const QChar& fillChar)

To fix this you either add the missing parameter (and use the expected fieldWidth of 3 instead of 2 as in your example)

QString paddedIdx(QString("%1").arg(idx, 3, 10, QChar('0')));

or use the more verbose construct

QString paddedIdx(QString::number(idx).rightJustified(3, QChar('0')));

BTW, it's rather easy to detect this behaviour using a debugger and stepping through the code. It would also be faster than writing up a SO question. Recommended reading: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/

Upvotes: 2

svm
svm

Reputation: 388

Use this: QString paddedIdx = QString("%1").arg(QString::number(idx), 3, QChar('0'));

Upvotes: 0

Related Questions