/// <summary>Encodes the provided data.</summary> /// <param name="toEncode">data to encode</param> /// <param name="ecBytes">error correction bytes</param> public void Encode(int[] toEncode, int ecBytes) { if (ecBytes == 0) { throw new ArgumentException("No error correction bytes"); } int dataBytes = toEncode.Length - ecBytes; if (dataBytes <= 0) { throw new ArgumentException("No data bytes provided"); } GF256Poly generator = BuildGenerator(ecBytes); int[] infoCoefficients = new int[dataBytes]; Array.Copy(toEncode, 0, infoCoefficients, 0, dataBytes); GF256Poly info = new GF256Poly(field, infoCoefficients); info = info.MultiplyByMonomial(ecBytes, 1); GF256Poly remainder = info.Divide(generator)[1]; int[] coefficients = remainder.GetCoefficients(); int numZeroCoefficients = ecBytes - coefficients.Length; for (int i = 0; i < numZeroCoefficients; i++) { toEncode[dataBytes + i] = 0; } Array.Copy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.Length); }
/// <summary>Create a representation of GF(256) using the given primitive polynomial.</summary> /// <param name="primitive"> /// irreducible polynomial whose coefficients are represented by /// the bits of an int, where the least-significant bit represents the constant /// coefficient /// </param> private GF256(int primitive) { // x^8 + x^4 + x^3 + x^2 + 1 // x^8 + x^5 + x^3 + x^2 + 1 expTable = new int[256]; logTable = new int[256]; int x = 1; for (int i = 0; i < 256; i++) { expTable[i] = x; x <<= 1; // x = x * 2; we're assuming the generator alpha is 2 if (x >= 0x100) { x ^= primitive; } } for (int i = 0; i < 255; i++) { logTable[expTable[i]] = i; } // logTable[0] == 0 but this should never be used zero = new GF256Poly(this, new int[] { 0 }); one = new GF256Poly(this, new int[] { 1 }); }
private GF256Poly BuildGenerator(int degree) { if (degree >= cachedGenerators.Count) { GF256Poly lastGenerator = cachedGenerators[cachedGenerators.Count - 1]; for (int d = cachedGenerators.Count; d <= degree; d++) { GF256Poly nextGenerator = lastGenerator.Multiply(new GF256Poly(field, new int[] { 1, field.Exp(d - 1) })); cachedGenerators.Add(nextGenerator); lastGenerator = nextGenerator; } } return(cachedGenerators[degree]); }