Modbus Register Scaling, Signed Values and 32-bit Floats in Kotlin

Short answer: a Modbus register is an unsigned 16-bit number. To get a real value you may need to treat it as signed, apply a scale factor from the manual (such as 0.1), or combine two registers into a 32-bit integer or float. Word order for two-register values differs between devices.

1. Scale factors

Devices often send integers with a fixed scale. A voltage register holding 2305 with a scale of 0.1 means 230.5 V.

val voltage = raw * 0.1   // raw is Int from the register

2. Signed 16-bit values

Values like temperature or current can be negative. The register still holds 16 bits, so convert it to a signed short.

fun toSigned16(raw: Int): Int = raw.toShort().toInt()

toSigned16(0xFFFE)   // -2
toSigned16(0x0064)   // 100

3. 32-bit values across two registers

Energy counters and power often use two consecutive registers.

fun toUnsigned32(high: Int, low: Int): Long =
    ((high.toLong() and 0xFFFF) shl 16) or (low.toLong() and 0xFFFF)

fun toSigned32(high: Int, low: Int): Int = toUnsigned32(high, low).toInt()

fun toFloat32(high: Int, low: Int): Float =
    Float.fromBits(toUnsigned32(high, low).toInt())

4. Word order

Within each register, Modbus sends the high byte first. Between the two registers, manufacturers differ: some put the high word first, others the low word first. If a 32-bit value looks wrong, swap the two registers and try again.

val value = toUnsigned32(low, high)   // swapped word order

5. Checklist when a value looks wrong

  1. Is it signed? Try toSigned16.
  2. Is there a scale factor in the manual?
  3. Is it a 32-bit value spanning two registers?
  4. Try swapped word order.
  5. Is the register address off by one?

FAQ

Why do I get 65535 instead of -1?

You are reading the 16 bits as unsigned. Convert to a signed short.

How do I read a float from Modbus?

Combine two registers into 32 bits and convert with Float.fromBits, after checking the device’s word order.

Related: Modbus RTU Basics for Android Developers and the Bluetooth and IoT hub.

Register maps differ by manufacturer. Always confirm addresses, scaling and word order in your device manual.