I'm trying to convert this MATLAB function into c# but my results are not as expected.
Can anyone see where I've gone wrong?
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;
}
}