Modbus float32 word order, and the off-by-one that reads almost right
Four ways to store a float in two Modbus registers, how to tell them apart in a hex dump, and the shifted address that reads almost right.
You connect an energy meter, read the L1 voltage and get 4.1738e-08. Every
Modbus integrator has seen this. The usual fix is to swap the two registers,
and the meter shows 230.2 V. Done.
A colleague connects the same meter and never sees the strange number. Their tool counts registers from 1, so it reads one register later. With the default word order, the meter shows 230.8 V straight away. Two mistakes, the address and the word order, cancel out almost completely. The values come out within 0.8 % of the truth, pass every plausibility check, and stay wrong for years.
This article covers the four byte layouts you meet in the field, how to recognise each one in a raw hex dump, and why the shifted address hides so well. It ends with a check that catches it every time. All numbers below come from a simulated meter, so you can reproduce them.
Why there are four orders at all
The Modbus specification defines 16-bit registers and says they are sent big-endian: high byte first. It does not define how a 32-bit value is split across two registers. Every vendor decided that for themselves.
The usual names come from the four bytes of the big-endian value. Take
230.2 V as an IEEE 754 float32: the bytes are 43 66 33 33. Call them A B C
D. Then there are four ways to put them into two registers:
| order | register n | register n+1 | also called |
|---|---|---|---|
| ABCD | 4366 | 3333 | big-endian, “high word first”, the Modbus default |
| CDAB | 3333 | 4366 | word-swapped, “low word first” |
| BADC | 6643 | 3333 | byte-swapped |
| DCBA | 3333 | 6643 | little-endian |
ABCD is the most common. Eastron’s SDM630 meter, for example, documents its floats this way. CDAB is common on energy meters and on devices whose firmware stores a little-endian 32-bit value and copies it out one 16-bit word at a time. BADC and DCBA are rarer, but they turn up in gateways and in firmware that swaps bytes once too often.
What each wrong order looks like
The wrong order does not raise an error. It returns a valid float, just an absurd one. Here is 230.2 V from a CDAB meter, decoded all four ways:
| decoded as | value |
|---|---|
| ABCD | 4.1738e-08 |
| CDAB | 230.2 |
| BADC | 4.17697e-08 |
| DCBA | 2.30451e+23 |
Two traps are hiding here.
Round numbers read as zero. 230.0 V is 43 66 00 00: the low word is
zero. Decoded with the word swap wrong, it becomes 2.4178e-41. That is a
tiny denormal number, and a dashboard with two decimals shows it as
0.00 V. On the bench, with a calibrator that delivers exactly 230.0 V,
the problem looks like “the meter reads zero”, not “the decoding is wrong”.
A byte swap can look plausible. It depends on the value. 49.98 Hz
read with the bytes swapped is 49797.9 Hz, which is obviously wrong. But every
float32 between 48.5 and 48.75 has the high word 4242. Swapping the bytes
of 4242 gives 4242 again, so only the low word changes. Such a frequency
read byte-swapped stays within 0.25 Hz of the truth. 48.6 Hz even comes out
as 48.599998, because its low word 6666 is symmetric too. One reading that
looks right is not proof.
Reading the hex instead of guessing
Decoding in all four orders and picking the one that looks sane works most of the time. Looking at the raw registers is faster and more reliable.
For a positive float32 between 0.5 and about 131,000, the first byte is
between 3F and 47. Negative values in the same range start with BF to
C7. Most engineering values fall in this range: volts, amps, hertz, degrees,
bar. Values below 0.5, such as a low power factor, start lower. So dump a block of registers and look for those bytes. Here is the
start of the meter’s input registers, with
modbus-sim running the simulated
meter:
$ modbus-sim read input 0 -c 4
input 0: 13107 [3333]
input 1: 17254 [4366]
input 2: 52429 [cccd]
input 3: 17253 [4365]
4366 and 4365 are clearly the “high halves” of two similar voltages. They
sit in the second register of each pair. 3333 and cccd look random:
they are low halves. So the high word comes second: that is CDAB. The pattern
for all four:
43 66in the first register of a pair: ABCD43 66in the second register: CDAB66 43in the first register: BADC66 43in the second register: DCBA
Note the words “of a pair”. This rule only works if you know where the pairs start. That is the subject of the next section.
Decoding all four in Python
Older pymodbus code used BinaryPayloadDecoder with byteorder and
wordorder arguments. You will still find it in many answers online.
pymodbus 3.10 removed it. Its replacement, convert_from_registers, only
knows word_order="big" (ABCD) and "little" (CDAB). It has no byte swap.
So here is a small helper that turns any of the four orders into ABCD and
then unpacks with struct:
# wordorder.py
"""32- and 64-bit Modbus values in any of the four word/byte orders."""
import struct
ORDERS = ("ABCD", "CDAB", "BADC", "DCBA")
def to_abcd(registers, order):
"""Registers as the device sends them -> the same registers in ABCD order."""
regs = list(registers)
if order in ("BADC", "DCBA"): # bytes swapped inside each register
regs = [((r & 0xFF) << 8) | (r >> 8) for r in regs]
if order in ("CDAB", "DCBA"): # registers in reverse order
regs.reverse()
return regs
def decode(registers, order, fmt=">f"):
"""fmt is a big-endian struct format: >f float32, >i int32, >Q uint64, >d float64."""
regs = to_abcd(registers, order)
return struct.unpack(fmt, struct.pack(f">{len(regs)}H", *regs))[0]
decode(rr.registers, "CDAB") gives 230.2 for the registers above. The same
function handles int32, uint32 and the 64-bit types. For 64-bit values,
“CDAB” here means all four registers reversed, which is also what pymodbus’
word_order="little" does. Not every device means the same by it, so check a
64-bit value against a known number before you trust it.
The off-by-one that looks like a fix
Manuals rarely give protocol addresses. They give register numbers like “30001: L1 voltage”. In the classic Modicon convention, the leading 3 means input register, and the numbering starts at 1. So 30001 is protocol address 0. But some manuals count from 0, some list hex addresses, and some tools expect the register number and subtract 1 themselves. Being one register off is the most common Modbus mistake after the word order.
Now combine the two. The meter stores CDAB, and the integrator reads address 1 instead of 0, with the default ABCD decoding:
$ modbus-sim read input 1 -c 3 -t float32
input 1: 230.8 [4366 cccd]
input 3: 229.1 [4365 199a]
input 5: 231.4 [4367 6666]
The true values are 230.2, 229.8 and 231.1 V. The readings are off by 0.6, 0.7 and 0.3 V, which looks like normal measurement noise. Nobody reopens that ticket.
Here is why. Reading one register late, each value takes its high word
from the right point (4366, the high half of L1) and its low word from the
next point (cccd, the low half of L2). For a float32, the high word holds
the sign, the exponent and the top 7 bits of the mantissa. The low word only
holds the lower 16 mantissa bits. Their weight is less than 1/128 of the
value. So a float with the right high word and any low word at all is within
0.78 % of the true value, whatever the neighbour holds.
The mirror case exists too. On an ABCD meter, reading one register early and decoding as CDAB gives the same kind of almost-right value. Reading one register late and decoding as CDAB does something different: it shows the next point. With the simulated meter switched to ABCD, “L3 voltage” then reads 10.38: the high half of the L1 current. That one at least looks wrong.
So for any float32, there are two readings that come out right or almost right: the right address with the right order, and the shifted address with the opposite word swap. Both pass a plausibility check. A range check on the value cannot tell them apart, and neither can the hex pattern from the previous section.
Telling them apart: one exact value
The only thing the wrong combination gets wrong is the low word. So you need a check that looks at the low word, which means a value you know exactly. A plausible range is not enough.
Good candidates on most devices:
- a serial number stored as a 32-bit integer: it is printed on the nameplate, and you can compare it digit by digit
- a text register (model name, firmware version): one register late, it is missing its first two characters
- a configuration value with a non-zero low word, such as a CT ratio of 150.5 that you entered on the front panel. A round value like 1.0 or 100.0 does not help: its low word is zero, and the neighbour’s low half may be zero as well
- an example frame in the manual: if it says
01 04 00 00 00 02reads L1 voltage, the address is 0, without any guessing
Here is a small probe that tries both address conventions and all four orders. For each one it checks two plausible values and one exact value, the serial number:
# probe.py
"""Which address convention and word order make the known values come out right?"""
import math
import sys
from pymodbus.client import ModbusTcpClient
from wordorder import ORDERS, decode
def near(expected, tolerance):
return lambda v: math.isfinite(v) and abs(v - expected) <= tolerance * abs(expected)
# Register number from the manual: (name, struct format, check)
KNOWN = {
30001: ("L1 voltage", ">f", near(230.0, 0.10)), # nominal +/- 10 %
30013: ("frequency", ">f", near(50.0, 0.01)), # +/- 1 %
30015: ("serial no.", ">I", lambda v: v == 21093117), # from the nameplate
}
def probe(client, unit):
passing = None
for number, (name, fmt, check) in KNOWN.items():
found = set()
for first in (30001, 30000): # register 30001 is address 0 ... or 1?
address = number - first
rr = client.read_input_registers(address, count=2, device_id=unit)
if rr.isError():
continue
for order in ORDERS:
value = decode(rr.registers, order, fmt)
if check(value):
found.add((first, order))
print(f"{name:<11} address {address:>2} {order} {value:.8g}")
passing = found if passing is None else passing & found
return passing
if __name__ == "__main__":
port, unit = int(sys.argv[1]), int(sys.argv[2])
client = ModbusTcpClient("127.0.0.1", port=port, timeout=1, retries=0)
client.connect()
for first, order in sorted(probe(client, unit)):
print(f"=> register {first} is address {30001 - first}, word order {order}")
client.close()
Against the simulated CDAB meter:
$ python probe.py 5020 1
L1 voltage address 0 CDAB 230.2
L1 voltage address 1 ABCD 230.8
frequency address 12 CDAB 49.98
frequency address 13 ABCD 49.963856
serial no. address 14 CDAB 21093117
=> register 30001 is address 0, word order CDAB
Both float checks pass twice, once for each combination. Only the serial number decides it: one register late, it reads 21055652 instead of 21093117. Even here the high word is right, and the number differs only in its last five digits. That is why the check has to be exact.
Make the order configuration, and test all four
The word order belongs to the device, not to your code. Put it in the device configuration next to the unit ID, and keep a single decoding path. Then test that path in every order, so no decode branch is left untested.
The simulated meter is a short YAML profile. modbus-sim can override the word order of each device in a bench:
# meter.yaml: a three-phase meter with fixed readings, float32 in CDAB word order
name: meter
description: fixed readings, float32 CDAB, serial number as uint32
word_order: CDAB
points:
- {name: voltage_l1, table: input, address: 0, type: float32, unit: V, value: 230.2}
- {name: voltage_l2, table: input, address: 2, type: float32, unit: V, value: 229.8}
- {name: voltage_l3, table: input, address: 4, type: float32, unit: V, value: 231.1}
- {name: current_l1, table: input, address: 6, type: float32, unit: A, value: 10.4}
- {name: current_l2, table: input, address: 8, type: float32, unit: A, value: 12.1}
- {name: current_l3, table: input, address: 10, type: float32, unit: A, value: 7.9}
- {name: frequency, table: input, address: 12, type: float32, unit: Hz, value: 49.98}
- {name: serial_number, table: input, address: 14, type: uint32, value: 21093117}
- {name: energy_import, table: input, address: 16, type: float32, unit: kWh, value: 1834.27}
The reader under test does one block read and takes the order as a parameter:
# meter_reader.py
from wordorder import decode
def read_meter(client, unit, order):
"""One block read of input registers 0-15; the word order comes from the config."""
rr = client.read_input_registers(0, count=16, device_id=unit)
if rr.isError():
raise IOError(f"unit {unit}: exception {rr.exception_code}")
regs = rr.registers
def value(address, fmt=">f"):
return decode(regs[address:address + 2], order, fmt)
return {
"voltage": [value(0), value(2), value(4)],
"current": [value(6), value(8), value(10)],
"frequency": value(12),
"serial": value(14, ">I"),
}
The test starts the same meter four times, once per order, through the pytest plugin that comes with modbus-sim:
# test_meter_reader.py
from pathlib import Path
import pytest
from pymodbus.client import ModbusTcpClient
from meter_reader import read_meter
from wordorder import ORDERS
PROFILE = str(Path(__file__).with_name("meter.yaml"))
@pytest.fixture(params=ORDERS)
def meter(request, modbus_bench_factory):
"""The same meter four times, once per word order."""
order = request.param
bench = modbus_bench_factory({"devices": [
{"profile": PROFILE, "unit": 1, "name": "meter", "word_order": order}]})
client = ModbusTcpClient("127.0.0.1", port=bench.port, timeout=0.5, retries=0)
client.connect()
yield client, order
client.close()
def test_reads_the_meter_in_every_word_order(meter):
client, order = meter
reading = read_meter(client, unit=1, order=order)
assert reading["voltage"] == pytest.approx([230.2, 229.8, 231.1], abs=1e-4)
assert reading["frequency"] == pytest.approx(49.98, abs=1e-4)
assert reading["serial"] == 21093117 # exact: catches a shifted address
$ pip install modbus-sim pymodbus pytest
$ pytest -q
.... [100%]
4 passed in 0.30s
The tolerance in approx is tight on purpose: 1e-4, not “within 1 %”.
A loose tolerance would let the almost-right reading through, as shown
above.
Checklist for the next device
- Dump the first few registers raw and find the
3F–47bytes. That tells you where the high words sit. - Find out where the pairs start: an example frame in the manual, a serial number, a text register. Do not trust a value that only “looks plausible”.
- Put the word order in the device configuration, not in the code.
- Test the decoding in all four orders, with exact expected values.
The code in this article was run against modbus-sim 0.2.2 and pymodbus 3.16.2. A simulator does not replace the commissioning check on the real device. But it lets you check the decoding and the address handling before the device arrives, and on every commit after that.