Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt Convert Negative Hex String to Signed Integer

Tags:

c++

signed

hex

qt

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;
like image 365
PhilBot Avatar asked Sep 04 '12 19:09

PhilBot


People also ask

How to represent negative hex numbers?

The hexadecimal value of a negative decimal number can be obtained starting from the binary value of that decimal number positive value. The binary value needs to be negated and then, to add 1. The result (converted to hex) represents the hex value of the respective negative decimal number.

Can you have a negative hexadecimal number?

A hex number is always positive (unless you specifically put a minus sign in front of it). It might be interpreted as a negative number once you store it in a particular data type. Only then does the most significant bit (MSB) matter, but it's the MSB of the number "as stored in that data type".

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


1 Answers

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;
like image 126
fasked Avatar answered Sep 22 '22 05:09

fasked