Question

I am reading the registers of an i2c device and the range of the return value is -32768 to 32768, signed integers. Below is an example:

# i2cget -y 3 0x0b 0x0a w
0xfec7

In Qt, I get this value ( 0xfec7 ) and want to display it in a QLabel as a signed integer. The variable stringListSplit[0] is a QString with the value '0xfec7'.

// Now update the label
int milAmps = stringListSplit[0].toInt(0,16); // tried qint32
qDebug() << milAmps;

The problem is no matter what I try I always get unsigned integers, so for this example I am getting 65223 which exceeds the maximum return value specified. I need to convert the hex value to a signed integer, so I need to treat the hex value as being expressed with 2s complement. I am not seeing a simple method in the QString documentation. How can I achieve this in Qt?

NOTE:

QString::toShort returns 0:

// Now update the label
short milAmps = stringListSplit[0].toShort(0,16);
qDebug() << "My new result: " << milAmps;

For an input of stringListSplit[0] equal to '0xfebe', I get an output of -322, using the C-style casting answered by Keith like so:

// Now update the label
int milAmps = stringListSplit[0].toInt(0,16);
qDebug() << "My new result: " << (int16_t)milAmps;
Was it helpful?

Solution

Cast your result to a signed 16-bit integer.

qDebug() << (int16_t)milAmps;

OTHER TIPS

You need to convert this string to 16-bit integer. It's most likely you can use QString::toShort method.

short milAmps = stringListSplit[0].toShort(0,16); 
qDebug() << milAmps;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top