I am working in a Modbus project where I have to read modbus Holding and Input registers using ESP8266, I am using ModbusMaster232 library. I returns a response buffer array of uint16_t. I need to convert the uint16_t to double precision float. A quick test in ESP8266 shows double datatype in ESP8266 stores 8 bytes.Does anybody know how to convert four uint16_t to double in Arduino. If so please share your knowledge.

1 Answer 1


Here's a code fragment for converting a uint16_t. Expand this to work with your array of ints from the library. Remember that on Arduino, - Uno and Mega, at least - doubles are implemented as floats. You won't get the precision you might be expecting.

double xAsDouble;    // ** only float precision despite 'double' declaration
uint16_t xAsInt;

xDouble = xInt;      // the compiler knows how to make this conversion.

Update: After re-reading your question, I realize you're using an ESP8266. My comments about Uno's float precision may not apply.

Update 2: After some discussion, I've learned that the Modbus return is not 4 integers, but a double being passed as 4 words, which need to be reassembled to recreate the original double. The solution will depend on the order in which the words comprising the original double are sent.

Update 3: I suggested the OP try using this general scheme:

// A union lets you look at memory as either (in this case) 4 ints or 1 double
union {
   uint16_t data_out[4];
   double x;
} buffer;

// Assign the data from modbus using the 'int' way of viewing menmory.
// Note I might have the ordering wrong but this is the idea:
buffer.data_out[i] = data_in[i];

Then reading 'buffer.x' would get the 4 words of memory as a double.

... After trying both orderings, the OP reports he is obtaining the expected result,

  • Thanks for reply @JRobert but I am using uint16_t array with 4 elements not a single uint16_t variable, I have to group this four 16 bit containers to a single 64 bit container representing IEEE754 float variable. Could you elaborate how the code would do that
    – Mr.B
    Apr 23, 2020 at 12:29
  • Do you understand how to use a for() loop to execute one or more statements over the members (items) in an array?
    – JRobert
    Apr 23, 2020 at 12:35
  • Do you mean uint16_t data_in={2121,1233,3435,2433}; double data_out=0; for(int i=0; i<4;i++) { data_out = data_out | data_in[i]<<16; }
    – Mr.B
    Apr 23, 2020 at 12:38
  • Yes - please see my edited comment above. You would do the same as in my example, but using [i] to address each of the ints and floats.
    – JRobert
    Apr 23, 2020 at 12:39
  • Is that code correct @JRobert ?
    – Mr.B
    Apr 23, 2020 at 12:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.