1. 程式人生 > >C#完整版CRC-16校驗演算法 CRC-16/MODBUS x16+x15+x2+1

C#完整版CRC-16校驗演算法 CRC-16/MODBUS x16+x15+x2+1

 public UInt16  Cal_crc16(byte[] data, int size)
        {

            UInt32 i = 0;
            UInt16 crc = 0;
            for (i = 0; i < size; i++)
            {
                crc = UpdateCRC16(crc, data[i]);
            }
            crc = UpdateCRC16(crc, 0);
            crc = UpdateCRC16(crc, 0);

            return (UInt16)(crc);
        }
        public UInt16  UpdateCRC16(UInt16  crcIn, byte  bytee)
        {
            UInt32  crc = crcIn;
            UInt32  ins =(UInt32)bytee | 0x100;

            do
            {
                crc <<= 1;
		       ins <<= 1;
                if ((ins & 0x100)==0x100 )
		       {
                    ++crc;
                }
                if ((crc & 0x10000)==0x10000)
                {
                    crc ^= 0x1021;
                }
            }
            while (!((ins&0x10000)==0x10000) );
            return (UInt16 )crc;
        }      

傳入引數為:byte[] array = new byte[] {0xbb,0xbb,0x43,0x43};

 private void button1_Click(object sender, EventArgs e)
        {
            CRC16_Verification crc16 = new CRC16_Verification();
            byte[] array = new byte[] {0xbb,0xbb,0x43,0x43};
            UInt16 crc = 0;
            crc = crc16.Cal_crc16(array, array.Length);
            tbxRawData.AppendText(crc.ToString());
     
        }

輸出結果為:C1 F8