qtqstringtwos-complement

Why QString("FFFFFFFF").toInt(0, 16); returns 0?


As you may know, 0xFFFFFFFF in the Two's Complement representation equals -1 (for 32 bits). But the following code:

qint32 aa = QString("FFFFFFFF").toInt(0, 16);
qDebug()<<aa;

prints 0. The code below:

qint32 aa = 0xffffffff;
qDebug()<<aa;

prints -1!

Why is this?


Solution

  • If you read the documentation you can see that toInt "Returns 0 if the conversion fails."

    Your input does not fit in a signed 32 bit integer, so presumably the conversion fails.

    You can verify this by using the ok-parameter:

    bool ok;
    qint32 aa = QString("FFFFFFFF").toInt(&ok, 16);
    if (ok) qDebug() << aa;
    else qDebug() << "Conversion failed!";