如何将此CRC校验从Matlab转换为c#?

时间:2009-03-08 20:56:23

标签: c# matlab

我正在尝试将此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;
    }
}

1 个答案:

答案 0 :(得分:3)

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];
}