示例#1
0
 /// <summary>
 /// Initializes the CRC-16 calculations.
 /// </summary>
 public override void Initialize()
 {
     if (this.definition.ReverseDataBytes)
     {
         this.remainder = HackersDelight.Reverse(this.definition.Initializer);
     }
     else
     {
         this.remainder = this.definition.Initializer;
     }
 }
示例#2
0
        /// <summary>
        /// Generates a lookup table for a CRC-16 algorithm definition. Both <see cref="Definition.TruncatedPolynomial"/> and <see cref="Definition.ReverseDataBytes"/> are used in the calculations.
        /// </summary>
        /// <param name="definition">The CRC-16 algorithm definition. May not be <c>null</c>.</param>
        /// <returns>The lookup table.</returns>
        public static ushort[] GenerateLookupTable(Definition definition)
        {
            Contract.Requires(definition != null);
            Contract.Ensures(Contract.Result <ushort[]>() != null);
            Contract.Ensures(Contract.Result <ushort[]>().Length == 256);

            unchecked
            {
                ushort[] ret = new ushort[256];

                byte dividend = 0;
                do
                {
                    ushort remainder = 0;

                    for (byte mask = 0x80; mask != 0; mask >>= 1)
                    {
                        if ((dividend & mask) != 0)
                        {
                            remainder ^= 0x8000;
                        }

                        if ((remainder & 0x8000) != 0)
                        {
                            remainder <<= 1;
                            remainder  ^= definition.TruncatedPolynomial;
                        }
                        else
                        {
                            remainder <<= 1;
                        }
                    }

                    if (definition.ReverseDataBytes)
                    {
                        var index = HackersDelight.Reverse(dividend);
                        Contract.Assume(index >= 0);
                        Contract.Assume(index <= 255);
                        ret[index] = HackersDelight.Reverse(remainder);
                    }
                    else
                    {
                        ret[dividend] = remainder;
                    }

                    ++dividend;
                }while (dividend != 0);

                return(ret);
            }
        }