简体   繁体   English

Qt将负十六进制字符串转换为有符号整数

[英]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. 我正在读取i2c设备的寄存器,返回值的范围是-32768到32768,有符号整数。 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. 在Qt中,我得到这个值(0xfec7)并希望将它作为有符号整数显示在QLabel中。 The variable stringListSplit[0] is a QString with the value '0xfec7'. 变量stringListSplit [0]是一个值为'0xfec7'的QString。

// 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. 问题是无论我尝试什么,我总是得到无符号整数,所以对于这个例子,我得到的65223超过了指定的最大返回值。 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. 我需要将十六进制值转换为有符号整数,因此我需要将十六进制值视为用2s补码表示。 I am not seeing a simple method in the QString documentation. 我没有在QString文档中看到一个简单的方法。 How can I achieve this in Qt? 我怎样才能在Qt中实现这一目标?

NOTE: 注意:

QString::toShort returns 0: QString :: toShort返回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: 对于stringListSplit [0]的输入等于'0xfebe',我得到-322的输出,使用由Keith回答的C风格的转换,如下所示:

// 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. 您需要将此字符串转换为16位整数。 It's most likely you can use QString::toShort method. 您最有可能使用QString::toShort方法。

short milAmps = stringListSplit[0].toShort(0,16); 
qDebug() << milAmps;

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

qDebug() << (int16_t)milAmps;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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