s4eed
s4eed

Reputation: 7891

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?

Upvotes: 1

Views: 2720

Answers (2)

Magnus Hoff
Magnus Hoff

Reputation: 22089

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!";

Upvotes: 5

lulyon
lulyon

Reputation: 7265

FFFFFFFF is not an integer format. 0xFFFFFFFF is. And also 0xFFFFFFFF is out of int range. Try use usigned integer. Change the conversion function toInt to toUInit. Here is the code:

quint32 aa = QString("0xffffffff").toUInt(0, 16);
quint32 bb = 0xffffffff;
qDebug()<<aa;
qDebug()<<bb;

It has been tested on my machine. The output is 4294967295.

Upvotes: 2

Related Questions