Search code examples
javamodbus-tcp

Java Programing on Modbus TCP to Convert 4 Integer Registers to Double value


Using java programming and with the help of Modbusutill(Jmod) jar I developed a code that it will connect to PLC through Modbus TCP. Here I got the situation that I need to convert 4 input registers to double value. Say registers are (16870,24900,1588,30492) and if i convert this i should get value like 3003782.9651476783. So for conversion i used method provided by library, here is the code,

byte[] bytes = {(byte) 16870,(byte) 24895,(byte) -32348,(byte) 617};
            double value = ModbusUtil.registersToDouble(bytes);
            System.out.println(value);

here i used ModbusUtil.registersToDouble(bytearray[]) method , and as a parameter im giving byte array. But this is not worked, i'm getting exception,

java.lang.ArrayIndexOutOfBoundsException: 4
    at net.wimpi.modbus.util.ModbusUtil.registersToDouble(ModbusUtil.java:326)
    at modbus.ReadDataFromPLC.realValue(ReadDataFromPLC.java:110)
    at modbus.ReadDataFromPLC.main(ReadDataFromPLC.java:11)

This is the exception im getting , anyone please help me how to convert 4 integers to get double value.

Thanks in advance.


Solution

  • According to the docs

    Converts a byte[8] binary double value into a double primitive.

    It explicitly specifies a byte array of length 8. Your array only has 4 bytes.

    It seems like that each of your numbers is not actually one byte. They are outside of the range -127~128. Each of your numbers might be two bytes combined. You might need to separate each of them into two bytes first, instead of blindly casting them to byte.

    Given a number x occupies 2 bytes, here is how to separate those bytes with shifts and masks:

    byte firstByte = (byte)(x >> 8);
    byte secondByte = (byte)(x & 0xff);
    

    Do this to all your numbers to get a total of 8 bytes.