Barracuda Barracuda - 19 days ago 5
C++ Question

QByteArray to Integer conversion produces incorrect results

I'm trying to convert a byte array to integer:

QByteArray b = QByteArray::fromHex("00008000");
quint32 result = b[3];
result += b[2] << 8;
result += b[1] << 16;
result += b[0] << 24;


but I'm getting
4294934528
instead of
32768
. What is the problem here?

Answer

QByteArray is an array of chars. Apparently, char on your platform is signed and 8-bit wide. Thus, your problem can be distilled to:

char c = 0x80;
quint32 = c << 8;

The standard mandates that:

N4606 ยง 4.8 [conv.integral] / 3

If the destination type is signed, the value is unchanged if it can be represented in the destination type; otherwise, the value is implementation-defined.

In this case (as usual on 2's complement systems), 0x80 is mapped to std::numeric_limits<char>::min() == -128, which is only logical because they share the same underlying bit pattern.

Now, -128 << 8 is defined as -128 * 28, which is -32768.

Finally, conversion from -32768 to 32 bit unsigned integer is well defined and yields 4294934528