威望0
积分7946
贡献0
在线时间763 小时
UID1
注册时间2021-4-14
最后登录2024-11-21
管理员
- UID
- 1
- 威望
- 0
- 积分
- 7946
- 贡献
- 0
- 注册时间
- 2021-4-14
- 最后登录
- 2024-11-21
- 在线时间
- 763 小时
|
[mw_shl_code=c,true]using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace crc16
{
class Program
{
static void Main(string[] args)
{
ushort crcresult = 0;
byte[] puchmsg = { 0x01,0x01,0x00,0x00, 0x00, 0x09 };
crcresult = CRC16_MODBUS(puchmsg,6);//MODBUS协议CRC16校验结果
string str_crc = string.Format("0x{0:X2}", crcresult);
Console.WriteLine("MODBUS输出结果:低8位:{0},高8位:{1}", Convert.ToString(crcresult & 0xff, 16), Convert.ToString((crcresult & 0xff00) >> 8, 16));
Console.WriteLine("MODBUS输出结果:{0}", str_crc);
Console.Read();
}
static ushort CRC16_MODBUS(byte[] puchMsg, int usDataLen)
{
ushort wCRCin = 0xFFFF;
ushort wCPoly = 0x8005;
byte wChar = 0;
byte a = 0;
for (int j = 0; j < usDataLen;j++ )
{
wChar = puchMsg[j];
wChar = InvertUint8(wChar);
wCRCin ^= (ushort)(wChar << 8);
for (int i = 0; i < 8; i++)
{
if ((wCRCin & 0x8000)==0x8000)
wCRCin = (ushort)((wCRCin << 1) ^ wCPoly);
else
wCRCin = (ushort)(wCRCin << 1);
}
}
wCRCin = InvertUint16(wCRCin);
return (wCRCin);
}
static byte InvertUint8(byte inputdata)
{
byte a0 = 0;
for (int i = 0; i < 8; i++)
{
if ((inputdata & ((byte)Math.Pow(2, i))) == ((byte)Math.Pow(2, i)))
{
a0 |= (byte)Math.Pow(2, 7 - i);
}
else
{ a0 |= 0x00; }
}
return a0;
}
static ushort InvertUint16(ushort inputdata)
{
ushort a0 = 0;
for (int i = 0; i < 16; i++)
{
if ((inputdata & ((ushort)Math.Pow(2, i))) == ((ushort)Math.Pow(2, i)))
{
a0 |= (ushort)Math.Pow(2, 15 - i);
}
else
{ a0 |= 0x00; }
}
return a0;
}
}
}
[/mw_shl_code] |
|