根据字符串计算Modbus RTU的CRC

问题描述 投票:0回答:2

我有字符串:02 03 04 50 00 01。我需要计算此字符串的CRC。

我有一个计算CRC的功能:

public static UInt16 ModRTU_CRC(ushort[] buf, int len)
        {
            UInt16 crc = 0xFFFF;

            for (int pos = 0; pos < len; pos++)
            {
                crc ^= (UInt16)buf[pos];

                for (int i = 8; i != 0; i--)
                {
                    if ((crc & 0x0001) != 0)
                    {
                        crc >>= 1;
                        crc ^= 0xA001;
                    }
                    else
                        crc >>= 1;
                }
            }
            return crc;
        }

我想将字符串转换为ushort数组:

ushort[] result = cmd.Split(' ').Select(item => Convert.ToUInt16(item, 16)).ToArray();

但是将这样的数组返回给我:2 3 4 80 0 1

请告诉我如何正确计算CRC。

c# hex crc modbus crc16
2个回答
1
投票

似乎,您想将两个byte组合成ushort,即给定的 string cmd = "02 03 04 50 00 01";

您想要获得

{0x0203, 0x0405, 0x0001}

如果是这种情况,

using System.Linq; ... string cmd = "02 03 04 50 00 01"; ushort[] result = cmd .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select((value, index) => new { index, value = Convert.ToInt32(value, 16) }) .GroupBy(item => item.index / 2, item => item.value) .Select(group => (UInt16)(group.Aggregate((s, a) => s * 256 + a))) .ToArray();

让我们看看:

Console.WriteLine(string.Join(" ", data.Select(item => item.ToString("x4"))));

结果:

0203 0450 0001


0
投票
您的代码很好!并且02 03 0450 0001本质上与02 03 04 50 00 01相同,只要它们是十六进制数字...
© www.soinside.com 2019 - 2024. All rights reserved.