Convert from String to Long and from Hex to Dec and From standard to IEEE 754.

Hi All,

I'm interfacing with a peltier controller over RS232. I send serial messages to it and receive serial messages back.

This all works great.

I'm dealing with temperature so when I get Serial commands back as a string I convert them to a long and then from HEX to DEC and from standard to IEEE 754. This is finally in the right format for me to either perform maths on it or send it to my LCD display.

Everything works...also long as the temperature doesn't drop below 0. My code cannot deal with negative numbers so I must be using the wrong sort of conversion.

Here is my Code:

if(Serial.available() > 0)

    {
        line1 = Serial.readStringUntil('\r');
        line2 = Serial.readStringUntil('\r');
        HexDEC = strtol( &line2[1], NULL, 16);
        SPvar = *(float *)&HexDEC;
  
    }

The string, line1 contains just an echo back of the command I sent to receive it.

The string, line2 contains The temperature in HEX with an unprintable character in front of it.

The Long, HexDEC contains the decimal representation of the Hexadecimal number.

the Float, SPvar contains the final human readable temperature number in degrees C.

I know that when i read a temperature of say 25.0 C i get:

Line2 = " 41c80000"
HexDEC = 1103626240
SPVar = 25.00

But when i read a temperture of say -10.0 C i get:
Line2 = " c1200000"
HexDEC =18874368
SPvar = Nan

Using windows calculator i can see that HexDEC is wrong because c1200000 in HEX should equal 3240099840 in Decimal by I don't know why it isn't working properly.

Can anyone explain to me why it isn't working as I expect it or to or if i'm using the wrong sort of code, what code i should be using?

Cheers

Steve

I've realized my post is a bit convoluted (and I think i may have typed a number in wrong), all I really want to know is why hexadecimal numbers aren't being correctly converted to decimal numbers so I've made a much more simple bit of code:

String line1 = "$C1200000";
long HexDEC;

void setup() {
  Serial.begin(9600);
}

void loop() {
delay(1000);
HexDEC = strtol( &line1[1], NULL, 16);
Serial.println(HexDEC);
}

So Much more simply in this example, HexDEC = 2147483647 but should equal 3240099840. Does anyone know why this is happening?

Does anyone know why this is happening?

What happens if you do this?

char *line1 = "$C1200000";
long HexDEC;

void setup() {
  Serial.begin(9600);
}

void loop() {
delay(1000);
HexDEC = strtol( &line1[1], NULL, 16);
Serial.println(HexDEC);
}

Try unsigned long HexDEC and strtoul().

Thanks oqibidipo,

That works!

I have no idea why it works though. But after struggling for so long I now longer care!