Netty reads the basic type and a negative number appears to read the original message and print it

The value range of byte is -128~127, and the IoT protocol is as follows,

 If you use ByteBuf.readByte() to read, when the value exceeds 127, it will be read as a negative number;

ByteBuf.readUnsignedByte() should be used to read;

same

The value range of short is -32768~32767, occupying 2 bytes (-2 to the 15th power of 2 to 2 to the 15th power-1), the protocol is as follows:

 Use ByteBuf.readShort() to read two consecutive bytes. If the value exceeds 32767, it will also be read as a negative number;

Should use ByteBuf.readUnsignedShort() to read two consecutive bytes

 

    private void toLog(ByteBuf in) {
        ByteBuf copy = in.copy();
        int[] tmp = new int[copy.readableBytes()];
        List<String> strings = new ArrayList<>();
        for (int b : tmp) {
            b = copy.readUnsignedByte();
            strings.add(String.format("%2s", HexUtil.toHex(b)).replace(" ", "0"));
        }
        log.info(String.join(" ", strings));
    }

Guess you like

Origin blog.csdn.net/weixin_45623983/article/details/128581570