Search code examples
flutterdartmodbus

Convert two 16 Bit Registers to 32 Bit real value flutter


I am using a Modbus flutter lib, reading 2 registers I obtain:

[22136, 4660]

This means: 0x12345678 I need a function to convert it to a 32 bit real value: 305419896, in easymodbustcp library I found:

/**
        * Convert two 16 Bit Registers to 32 Bit real value
        * @param        registers   16 Bit Registers
        * @return       32 bit real value
        */
    public static float ConvertRegistersToFloat(int[] registers) throws IllegalArgumentException
    {
        if (registers.length != 2)
            throw new IllegalArgumentException("Input Array length invalid");
        int highRegister = registers[1];
        int lowRegister = registers[0];
        byte[] highRegisterBytes = toByteArray(highRegister);
        byte[] lowRegisterBytes = toByteArray(lowRegister);
        byte[] floatBytes = {
                                highRegisterBytes[1],
                                highRegisterBytes[0],
                                lowRegisterBytes[1],
                                lowRegisterBytes[0]
                            };
        return ByteBuffer.wrap(floatBytes).getFloat();
    }  

Any help to do it in flutter / dart?


Solution

  • This can be done with bit shifts and a bitwise or. You need to shift the 2 higher bytes by 16 bits, then or it to get the value you want.

    void main() {
      List<int> vals = [22136, 4660];
      
      int result = vals[1] << 16 | vals[0];
      print(result);//305419896
    }
    

    You could also achieve the same result in this case by replacing the bitwise or with addition.

    void main() {
      List<int> vals = [22136, 4660];
      
      int result = (vals[1] << 16) + vals[0];
      print(result);//305419896
    }