I got a Problem. I’ve got a MODBUS TCP answer, which is hex coded like this: 0 0 0 0 0 7 1 4 4 41 B8 66 64. For explanation: the first five zeroes are a specification of Modbus, the 7 are the numbers of bytes following after it. the 1 is the client address in the Modbus network and not relevant. the first 4 is the function code which is used. the second 4 is again the numbers of bytes following. The last four bytes is the hex coded answer, which should be converted to double. The array, in which this is stored is a unsigned char array.
Here a few examples how i tried it.
Here the first example:
value = (ibuf[9]<<24) + (ibuf[10]<<16) + (ibuf[11]<<8) + ibuf[12];
Value is the used double variable and ibuf the used char array.
Here the second one:
for(i = 0; i < k; i++)
{
if (i==0)
{
sprintf(ergebnis, "%x%x", ibuf[9], ibuf[10]);
}
else
{
//sprintf(buffer,"%x%x",ibuf[9+i+i], ibuf[10+i+i]);
//strcat( ergebnis, buffer );
sprintf(ergebnis, "0x41b451e8");
sscanf(ergebnis, "%l %lf ", &Value);
}
printf("Ergebnis %s\n", ergebnis);
}
Here I used a fixed value, but the problem is always the conversion from hex to double.
I’m glad about every help I could get.
You’re almost there. Unfortunately, conversion occurs automatically during promotion – the most “straightforward” way of circumventing this is through dereferencing a float pointer cast of an int, as so:
For the data supplied, this gives 23.049995 instead of 1.1026039e+009, which you get from conversion.
EDIT:
As Mike Seymour pointed out in the comment below, a preferred way to write this is:
Note that you cannot do this:
This will raise an error (as seen here in VS2005):