C# CRC16帮助类
/// <summary> /// CRC16 帮助类 /// </summary> public class CRC16Helper { /// <summary> /// CRC校验 /// </summary> /// <param name="data">校验数据</param> /// <returns>高低8位</returns> public static string CRCCalc(string data) { string[] datas = data.Split(' '); List<byte> bytedata = new List<byte>(); foreach (string str in datas) { bytedata.Add(byte.Parse(str, System.Globalization.NumberStyles.AllowHexSpecifier)); } byte[] crcbuf = bytedata.ToArray(); //计算并填写CRC校验码 int crc = 0xffff; int len = crcbuf.Length; for (int n = 0; n < len; n++) { byte i; crc = crc ^ crcbuf[n]; for (i = 0; i < 8; i++) { int TT; TT = crc & 1; crc = crc >> 1; crc = crc & 0x7fff; if (TT == 1) { crc = crc ^ 0xa001; } crc = crc & 0xffff; } } string[] redata = new string[2]; redata[1] = Convert.ToString((byte)((crc >> 8) & 0xff), 16); redata[0] = Convert.ToString((byte)((crc & 0xff)), 16); return data + " " + redata[0] + " " + redata[1]; } /// <summary> /// CRC校验 /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static byte[] CRC16(byte[] bytes) { //计算并填写CRC校验码 int crc = 0xffff; int len = bytes.Length; for (int n = 0; n < len; n++) { byte i; crc = crc ^ bytes[n]; for (i = 0; i < 8; i++) { int TT; TT = crc & 1; crc = crc >> 1; crc = crc & 0x7fff; if (TT == 1) { crc = crc ^ 0xa001; } crc = crc & 0xffff; } } var nl = bytes.Length + 2; //生成的两位校验码 byte[] redata = new byte[2]; redata[0] = (byte)((crc & 0xff)); redata[1] = (byte)((crc >> 8) & 0xff); //重新组织字节数组 var newByte = new byte[nl]; for (int i = 0; i < bytes.Length; i++) { newByte[i] = bytes[i]; } newByte[nl - 2] = (byte)redata[0]; newByte[nl - 1] = redata[1]; return newByte; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构