LKBEN11676: How to write a HRESULT value to a logfile in Qt/C++ as hexadecimal number.


Symptom

You need to write a hex number to a logfile.

Cause

By default the nummer will be written as decimal number.

Solution

Windows functions often return a hres (HRESULT) from a function call. This HRESULT is a typedef for a LONG. Most of the time these values are documented in hexadecimal form. If you write it to a logfile, your logfile will be repesented as a decimal number and you will have to convert it.

To write the HRESULT to a logfile and directly as hexadecimal, you can use the following code:

HRESULT hres;

QFile logfile("C:\\somefile.log");
logfile.open(QIODevice::WriteOnly);
QTextStream logstream(&logfile);

hres = some_functioncall(...);

if (FAILED(hres))
{
    logstream << "Error code = 0x" << Qt::hex << hres << Qt::endl;
    ....
}

This example does not compile on it's own because it is a part of a program. The Qt::hex does the job.

Have fun.

Disclaimer:

The information provided in this document is intended for your information only. Lubby makes no claims to the validity of this information. Use of this information is at own risk!

About the Author

Author: Wim Peeters - Keskon GmbH & Co. KG

Wim Peeters is electronics engineer with an additional master in IT and over 30 years of experience, including time spent in support, development, consulting, training and database administration. Wim has worked with SQL Server since version 6.5. He has developed in C/C++, Java and C# on Windows and Linux. He writes knowledge base articles to solve IT problems and publishes them on the Lubby Knowledge Platform.

Latest update: 08-09-2023