Qt 6.2.1 MinGW
I have 2 arrays, header FirstArray
and body SecondArray
. I know that copy-paste, isn't good in programming, so at first, did so :
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
const QByteArray FirstArray=QByteArray(std::begin<char>({static_cast<char>(0xA5), 0x5A, static_cast<char>(0xB5), 0x5B}), 4);
const QByteArray SecondArray=QByteArray(FirstArray std::begin<char>({0x18, 0x00, 0x01, static_cast<char>(0x9B), 0x03, 0x09, 0x00, 0x19, static_cast<char>(0x91)}), 13);
qDebug()<< SecondArray.toHex();
return a.exec();
}
I expected the result:
"a55ab55b1800019b0309001991"
But in output I see:
"a55ab55b1800adbaababababab"
Then I rewrite the second QByteArray
initialization, and remove plus operation in constructor:
const QByteArray SecondArray=QByteArray(std::begin<char>({static_cast<char>(0xA5), 0x5A, static_cast<char>(0xB5), 0x5B, 0x18, 0x00, 0x01, static_cast<char>(0x9B), 0x03, 0x09, 0x00, 0x19, static_cast<char>(0x91)}), 13);
I get:
"a55ab55b1800019b0309001991"
Why does it's happed in the first case? How to write correctly?
CodePudding user response:
As mentioned in a comment, you are calling
const QByteArray operator (const QByteArray &a1, const char *a2)
Which, per its documentation:
Returns a byte array that is the result of concatenating byte array a1 and string a2.
It excepts a2
to point to a null-terminated string.
You can rearrange the concatenation to
FirstArray QByteArray(std::begin<char>({0x18, ......
To call the other overload which does not rely on null-termination of a c-string.