【问题标题】:How can I convert this CRC check from Matlab to c#?如何将此 CRC 检查从 Matlab 转换为 c#?
【发布时间】:2009-03-08 20:56:23
【问题描述】:

我正在尝试将此 MATLAB 函数转换为 c# 但我的结果并不如预期。

MATLAB:

function check=CRC8(xa);
% xa is array of bits to be transmitted (column vector)
% Generates 8-bit CRC check with g(x) = x^8 + x^2 +x + 1
    xae = [xa;0;0;0;0;0;0;0;0]; % Append 8 zeros to array containing bit-stream
    g8x = [1;0;0;0;0;0;1;1;1] ; % Generator polynomial
    xsa=xae(1:9);
    for i=1:length(xa)
        if xsa(1) = = g8x(1), xsa = xor(xsa,g8x); end;
        xsa(1:8)=xsa(2:9);
        if i<length(xa) xsa(9)=xae(i+9); end;
    end;
    check = xsa(1:8); % 8 bit CRC column vector
    return;

C#

    public static int[] checkCRC8(int[] xa)
    {

        int[] g8x = { 1, 0, 0, 0, 0, 0, 1, 1, 1 };

        int[] xae = new int[xa.Length + 8];
        xa.CopyTo(xae, 0);
        //add zeros
        for (int i = xa.Length; i < xae.Length; i++)
        {
            xae[i] = 0;
        }

        int[] xsa = new int[8];
        for (int i = 0; i < 8; i++)
        {
            xsa[i] = xae[i];
        }

        for (int i = 0; i < xa.Length; i++)
        {
            if (xsa[0] == g8x[0])
            {
                //xor xsa with g8x
                for (int j = 0; j < xsa.Length; j++)
                {
                    xsa[j] = xsa[j] ^ g8x[j];
                }
            }
            //shift array elements left
            for (int j = 0; j < xsa.Length - 1; j++)
            {
                xsa[j] = xsa[j + 1];
            }

            if (i < xa.Length)
            {
                xsa[xsa.Length - 1] = xae[i + 8];
            }


        }
        return xsa;
    }
}

【问题讨论】:

    标签: c# matlab


    【解决方案1】:

    xsa = xae(1:9) 中的 matlab 范围包括在内,因此 xsa 应该有 9 个元素而不是 8 个。另外,由于您的 i 已经从零开始,我认为最后一个 if 应该与 xa.Length-1 进行比较,并使用 i+9 的数组元素而不是 i+8

    if (i < xa.Length - 1)
    {
       xsa[xsa.Length - 1] = xae[i + 9];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 2019-09-29
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多