Search code examples
javamodbus

How to read Long (Swapped) value from Modbus?


I need to read Long (swapped) value from Modbus register.

enter image description here

From picture above I want to read register 42002 which has value of 78146789. This is in Long (Swapped ) format. It looks like this in Decimal format:

enter image description here

I am using Java shorts array to read this. I am getting 1192,27877 correctly. Now I need to convert these values to proper value which is 78146789 in this case. How to do this? How is Long (Swapped) represented here ?


Solution

  • You can use a ByteBuffer to convert the shorts to a long. But you have to add the leading 0's

    public static void main(String[] args) {
        short x = 1192;
        short y = 27877;
        ByteBuffer bb = ByteBuffer.allocate(8);
        bb.clear();
        bb.putShort((short) 0);
        bb.putShort((short) 0);
        bb.putShort(x);
        bb.putShort(y);
        bb.flip();
        System.out.println("" + bb.getLong());
    }