简体   繁体   中英

Qt Convert Negative Hex String to Signed Integer

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;

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;

将结果转换为带符号的16位整数。

qDebug() << (int16_t)milAmps;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM