2009-03-08 10 views
1

J'essaye de convertir cette fonction de MATLAB en C# mais mes résultats ne sont pas comme prévu.Hwo puis-je convertir ce contrôle CRC de Matlab en C#?

Quelqu'un peut-il voir où je me suis trompé?

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

Répondre

3

Les gammes Matlab en xsa = xae(1:9) sont inclus, donc xsa devrait avoir neuf éléments au lieu de huit. De plus, puisque votre i est déjà base zéro, je pense que la dernière se doit de comparer contre xa.Length-1 et utiliser l'élément de tableau à i+9 au lieu de i+8:

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