You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何读取超出Qt Modbus InputRegisters范围的无符号整型数据?

Reading 32-bit Unsigned Integers with QModbusDataUnit

Great question! Since single Modbus input registers only hold 16-bit values (unsigned short, 0-65535), to get a 32-bit unsigned integer (0-4294967295), you’ll need to read two consecutive 16-bit input registers and combine them into a single 32-bit value. Here’s a step-by-step breakdown:

Step 1: Request Two Consecutive Input Registers

First, adjust your QModbusDataUnit to fetch 2 registers instead of 1. For example, if your 32-bit value starts at address 40006:

QModbusDataUnit readUnit(QModbusDataUnit::InputRegisters, 40006, 2);

Double-check that the starting address matches where your device stores the first half of the 32-bit value.

Step 2: Merge the 16-bit Values into a 32-bit Integer

Once you receive the result, you’ll need to combine the two 16-bit values. The most important detail here is endianness (byte order)—you must check your device’s Modbus documentation to confirm how it splits the 32-bit value across registers. The two common formats are:

Case 1: Big-Endian (Most Significant Word First)

This is the standard for most Modbus devices. The first register holds the high 16 bits, and the second holds the low 16 bits:

if (result.valueCount() == 2) {
    quint16 highWord = result.value(0);
    quint16 lowWord = result.value(1);
    quint32 full32BitValue = (static_cast<quint32>(highWord) << 16) | lowWord;
    // full32BitValue is your target unsigned int
}

Case 2: Little-Endian (Least Significant Word First)

Some devices store the low 16 bits first. Reverse the order when combining:

if (result.valueCount() == 2) {
    quint16 lowWord = result.value(0);
    quint16 highWord = result.value(1);
    quint32 full32BitValue = (static_cast<quint32>(highWord) << 16) | lowWord;
    // Alternatively:
    // quint32 full32BitValue = static_cast<quint32>(lowWord) | (static_cast<quint32>(highWord) << 16);
}

Critical Reminder

Always confirm the endianness in your device’s manual—using the wrong order will produce incorrect values. If you’re uncertain, test with a known value to validate which format your device uses.

内容的提问来源于stack exchange,提问作者user1157977

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:47:24