kochedykov / jlibmodbus

JLibModbus - is an implementation of the Modbus protocol v1.1b in java language. Java modbus library. It works. Welcome.
http://kochedykov.github.io/jlibmodbus/
Apache License 2.0
299 stars 128 forks source link

The problem of transforming byte[] into int[] #64

Closed danghongen closed 7 months ago

danghongen commented 3 years ago

Dear author, I like your open source works very much, but I found some small problems in the process of using them.

1、Classpath: src/com/intelligt/modbus/jlibmodbus/utils/DataUtils.java

2、methodName: BeToIntArray(byte[] bytes);

3、sourceCode:

static public int[] BeToIntArray(byte[] bytes) {
        int[] dst = new int[bytes.length / 2];
        for (int i = 0, j = 0; i < dst.length; i++, j += 2)
            dst[i] = ((bytes[j] & 0xff) << 8) | (bytes[j + 1] & 0xff);
        return dst;
    }

4、Explain: When I invoke the method in the process of using, I found that the value returned is wrong; int in Java is the 32 bit basic data type, and byte is the data type of 8 bits. So when the byte array is turned to int, should it be 4 byte bytes converted to one data?

5、Personal suggestion revision code (when the high position is in the front and the low position is in the back):

static public int[] BeToIntArray(byte[] bytes) {
        int[] dst = new int[bytes.length / 4];
        int i = 0;
        for (int j = 0; i < dst.length; j += 4) {
            dst[i] = ((bytes[j] )<< 24) |
                    ((bytes[j + 1] & 0xFF) << 16)
                    | ((bytes[j + 2] & 0xFF) << 8)
                    | ((bytes[j + 3]) & 0xFF);
            ++i;
        }
        return dst;
    }
kochedykov commented 7 months ago

The library uses integers for registers. It is possible to create a method to get 32 bit array.

So I've just renamed BeToIntArray to BeToRegArray and added BeToIntArray:

static public int[] BeToRegArray(byte[] bytes) { int[] dst = new int[bytes.length / 2]; for (int i = 0, j = 0; i < dst.length; i++, j += 2) dst[i] = ((bytes[j] & 0xff) << 8) | (bytes[j + 1] & 0xff); return dst; }

static public int[] BeToIntArray(byte[] bytes) throws IllegalRangeException {
    if (bytes.length % 4 != 0) {
        throw new IllegalRangeException();
    }
    int[] dst = new int[bytes.length / 4];
    for (int i = 0, j = 0; i < dst.length; i++, j += 4)
        dst[i] = ((bytes[j] )<< 24)             |
                 ((bytes[j + 1] & 0xFF) << 16)  |
                 ((bytes[j + 2] & 0xFF) << 8)   |
                 ((bytes[j + 3]) & 0xFF);

    return dst;
}