Floats, longs and byte order
Need: the device stores a float or a 32-bit integer in two registers, and its word order is not the standard ABCD. The script has to read and write in the device's order.
The example first simulates the raw data the device holds:
| Address | Raw registers | Meaning |
|---|---|---|
0x0200..0x0201 | 0x8000, 0x4366 | Voltage 230.5, float CDAB (low word first) |
0x0202..0x0203 | 0xE240, 0x0001 | Energy 123456, long CDAB |
0x0204 | 0xFF83 | Temperature −12.5 °C, stored in 0.1 °C units as signed −125 |
| Case | What it does |
|---|---|
| Device data | Writes the raw registers in the table with FC16 |
| Read in the device order | Reads the voltage as float_cdab (tolerance 0.1), the energy as long_cdab, and the temperature as signed, then divides by 10 |
| Find the byte order | Reads the same registers as both float_abcd and float_cdab to see which makes sense |
| Write in the device order | Writes 12.5 as float_cdab, then reads back the raw registers |

What the Log shows:
| Case | Log |
|---|---|
| Read in the device order | Temperature = -12.5 C |
| Find the byte order | float_abcd = -2.4178e-41, float_cdab = 230.5 |
| Write in the device order | 12.5 as float_cdab = 0, 16712 (16712 = 0x4148) |
How to tell which order the device uses: read a known value (the rated voltage, for example) as float_abcd, float_cdab and the other formats. The one that gives a sensible result is the right order. The wrong order usually gives a tiny number (such as -2.4178e-41) or a huge one.
Notes
- When comparing floats, add a
toleranceso rounding does not cause a FAIL. - The format only changes how the registers are interpreted, not the data in the device. Each format is described in Concepts › 8. Value formats and byte order.
Download the sample script
Sample script
Before running it, start a Slave window on 127.0.0.1:502 and click Listen, then open the script with Open JSON in Script mode and click Run. See How to use the examples.
