Pergunta

Eu estou tentando converter essa função MATLAB em c # mas meus resultados não são os esperados.

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;
    }
}
Foi útil?

Solução

As faixas de Matlab como em xsa = xae(1:9) são inclusivas, de modo xsa deve ter nove elementos em vez de oito. Além disso, desde a sua i já é baseado em zero, eu acho que a última se deve comparar contra xa.Length-1 e usar o elemento da matriz em i+9 vez de i+8:

if (i < xa.Length - 1)
{
   xsa[xsa.Length - 1] = xae[i + 9];
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top