Important: Please read the Qt Code of Conduct -

2's complement convertion

  • Hello,

    I have build a programm that gets some data from a modbus device.
    The modbus device sends its data with the 2's complement way.

    How can i convert the incoming value to a normal integer?

    This is what is given with the device:

    Extended addressing
    The panels use extended (32-bit) addressing format.
    Value = (65536 * MSW) + LSW
    How to interpret the values
    The two's complement of the value is used.
    32 bit example: 1 is represented as 0b00000000_00000000_00000000_00000001
    32 bit example: -1 is represented as 0b11111111_11111111_11111111_11111111

    This is the code i have now:

    auto replyIR = qobject_cast<QModbusReply *>(sender());
    const QModbusDataUnit unit = replyIR->result();
    uint32_t test2 = (unit.value(1)<<16) | unit.value(0);

    (this works the same as (65536 * unit.value(1)) + unit.value(0); )

    This works fine for positive numbers. The problem is the negative numbers.
    How can i read all the numbers?

  • Moderators

    @GhostWolf said in 2's complement convertion:

    uint32_t test2 = (unit.value(1)<<16) | unit.value(0);

    Just store the result as a signed integer (int32_t) instead of unsigned (uint32_t).

    You don't need to change the bit pattern (0b11111111_11111111_11111111_11111111).

    • Interpreting this pattern as Unsigned gives you ‭4294967295
    • Interpreting this pattern as Signed gives you -1.