How to convert a pointer value to QString?

Martin Hennings picture Martin Hennings · Jan 16, 2012 · Viewed 23.3k times · Source

for debug purposes I often output pointer values (mostly this) to qDebug:

qDebug("pointer of current object = 0x%08x",this);, using "%08x" as format string and simply passing this as a parameter.

How can I convert the pointer value to a QString?

This is what I got so far:

char p = (char)this;
return QString("0x%1").arg(p, 8, '0');

But the compiler doesn't seem to figure out what to do with that value. Is casting to char correct in this case? Or what would be a safer way to do this?

Using Visual C++ with Qt 4.7.4.

EDIT

Using qulonglong as suggested

qulonglong p = (qulonglong)this;
return QString("0x%1").arg(p, 8, '0');

yields in a compiler error message (error C2666).

Answer

Ignitor picture Ignitor · May 15, 2013

Using QString::arg():

MyClass *ptr = new MyClass();
QString ptrStr = QString("0x%1").arg((quintptr)ptr, 
                    QT_POINTER_SIZE * 2, 16, QChar('0'));

It will use the correct type and size for pointers (quintptr and QT_POINTER_SIZE) and will always prefix "0x".

Notes:
To prefix the value with zeros, the fourth parameter needs to be QChar('0').
To output the correct number of digits, QT_POINTER_SIZE needs to be doubled (because each byte needs 2 hex digits).