C#实现 CRC-16 验证算法

 

C语言:

CRC-16 验证算法: ***************************************************************************

unsigned int CRC16_Checkout ( unsigned char *puchMsg, unsigned int usDataLen )

{

unsigned int i,j,crc_reg,check;

 

crc_reg = 0xFFFF;

for(i=0;i<usDataLen;i++)

 {

crc_reg = (crc_reg>>8) ^ puchMsg[i];

for(j=0;j<8;j++)

{

check = crc_reg & 0x0001;

crc_reg >>= 1;

if(check==0x0001)

{

crc_reg ^= 0xA001;

}

}

}

return crc_reg;

}

示例:

##0101QN=20160801085857223;ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5 ;CP=&&RtdInterval=30&&1C80\r\n,其中 1C08 为 CRC16 校验码,是对数据段 QN=20160801085857223; ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&& 进 行 CRC16 校验所得的校验码。

 

C#:

 class Program
    {
        static void Main(string[] args)
        {


            string data = "QN=20160801085857223;ST=32;CN=1062;PW=100000;MN=010000A8900016F000169DC0;Flag=5;CP=&&RtdInterval=30&&";
                
                string crc = CRC16(System.Text.Encoding.UTF8.GetBytes(data));

            Console.ReadKey();

        }


        public static string CRC16(byte[] data)
        {
            ushort crc = 0xFFFF;
            int len = data.Length;
            for (int i = 0; i < len; i++)
            {
                crc = (ushort)((crc >> 8) ^ data[i]);
                for (int j = 0; j < 8; j++)
                    crc = (crc & 1) == 1 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
            }
            return string.Format("{0:X}", crc).PadLeft(4, '0');
        }


    }

 

 

来源:

https://www.cnblogs.com/sheng9hhd/p/13194293.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值