JT/T808校验码计算(按字节异或求和)

JT/T808组包的最重要一个环节之一就是对整个包(除去包头包尾的0x7E)内容按字节异或求和。

C# 实现

        public int getXorCode(byte[] data)
        {
            byte CheckCode = 0;
            int len = data.Length;
            for (int i = 0; i < len; i++)
            {
                CheckCode ^= data[i];
            }
            return CheckCode;
        }

传入参数为byte[]

Java 实现

    public int getXorCode(ByteBuf buf) {
        int checksum = 0;
        while (buf.readableBytes() > 0) {
            checksum ^= buf.readUnsignedByte();
        }
        return checksum;
    }

传入的是ByteBuf,基于的是Netty框架

如果想传入的也是byte[],则如下:

    public static int getXorCode(byte[] bytes) {
        int checksum = 0;
        for (byte b : bytes) {
            checksum ^= b;
        }
        return checksum;
    }

猜你喜欢

转载自blog.csdn.net/qq_17486399/article/details/117666020
今日推荐