My program received messages from a network as an array of bytes. The sender of the messages encoded integers in Big Endian format. So, the hex number 0x1540 arrived in the sequence [0x15, 0x40]. I wrote the following function, which converts such a byte array of at most four bytes into a 32-bit unsigned integer. The function converts the sequence [0x15, 0x40] into the hex number 0x1540.
quint32 byteArrayToUint32(const QByteArray &bytes)
{
auto count = bytes.size();
if (count == 0 || count > 4) {
return 0;
}
quint32 number = 0U;
for (int i = 0; i < count; ++i) {
auto b = static_cast<quint32>(bytes[count - 1 - i]);
number += static_cast<quint32>(b << (8 * i));
}
return number;
}
Of course, I also wrote a unit test.
void TestByteArrayToUint32::testByteArrayToUint32()
{
QCOMPARE(byteArrayToUint32(QByteArray::fromHex("9020562f")), 0x9020562fU);
QCOMPARE(byteArrayToUint32(QByteArray::fromHex("314922")), 0x314922U);
QCOMPARE(byteArrayToUint32(QByteArray::fromHex("1540")), 0x1540U);
QCOMPARE(byteArrayToUint32(QByteArray::fromHex("38")), 0x38U);
QCOMPARE(byteArrayToUint32(QByteArray::fromHex("")), 0x0U);
QCOMPARE(byteArrayToUint32(QByteArray::fromHex("559020562f")), 0x0U);
}
All QCOMPARE checks passed. All seemed fine. After using my function for a (short) while, a test didn't want to pass. I tracked the problem down to my function. Converting the byte array [0x01, 0x80] yielded the result 0x80.
Can you spot the bug in my code - and in my test?
Read More »Converting a QByteArray into an Unsigned Integer