1. /// <summary>
  2. /// CRC校验
  3. /// </summary>
  4. public class CRC
  5. {
  6.  
  7. #region CRC16
  8. public static byte[] CRC16(byte[] data)
  9. {
  10. int len = data.Length;
  11. if (len > 0)
  12. {
  13. ushort crc = 0xFFFF;
  14.  
  15. for (int i = 0; i < len; i++)
  16. {
  17. crc = (ushort)(crc ^ (data[i]));
  18. for (int j = 0; j < 8; j++)
  19. {
  20. crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
  21. }
  22. }
  23. byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
  24. byte lo = (byte)(crc & 0x00FF); //低位置
  25.  
  26. return new byte[] { hi, lo };
  27. }
  28. return new byte[] { 0, 0 };
  29. }
  30. #endregion
  31.  
  32. #region ToCRC16
  33. public static string ToCRC16(string content)
  34. {
  35. return ToCRC16(content, Encoding.UTF8);
  36. }
  37.  
  38. public static string ToCRC16(string content, bool isReverse)
  39. {
  40. return ToCRC16(content, Encoding.UTF8, isReverse);
  41. }
  42.  
  43. public static string ToCRC16(string content, Encoding encoding)
  44. {
  45. return ByteToString(CRC16(encoding.GetBytes(content)), true);
  46. }
  47.  
  48. public static string ToCRC16(string content, Encoding encoding, bool isReverse)
  49. {
  50. return ByteToString(CRC16(encoding.GetBytes(content)), isReverse);
  51. }
  52.  
  53. public static string ToCRC16(byte[] data)
  54. {
  55. return ByteToString(CRC16(data), true);
  56. }
  57.  
  58. public static string ToCRC16(byte[] data, bool isReverse)
  59. {
  60. return ByteToString(CRC16(data), isReverse);
  61. }
  62. #endregion
  63.  
  64. #region ToModbusCRC16
  65. public static string ToModbusCRC16(string s)
  66. {
  67. return ToModbusCRC16(s, true);
  68. }
  69.  
  70. public static string ToModbusCRC16(string s, bool isReverse)
  71. {
  72. return ByteToString(CRC16(StringToHexByte(s)), isReverse);
  73. }
  74.  
  75. public static string ToModbusCRC16(byte[] data)
  76. {
  77. return ToModbusCRC16(data, true);
  78. }
  79.  
  80. public static string ToModbusCRC16(byte[] data, bool isReverse)
  81. {
  82. return ByteToString(CRC16(data), isReverse);
  83. }
  84. #endregion
  85.  
  86. #region ByteToString
  87. public static string ByteToString(byte[] arr, bool isReverse)
  88. {
  89. try
  90. {
  91. byte hi = arr[0], lo = arr[1];
  92. return Convert.ToString(isReverse ? hi + lo * 0x100 : hi * 0x100 + lo, 16).ToUpper().PadLeft(4, '0');
  93. }
  94. catch (Exception ex) { throw (ex); }
  95. }
  96.  
  97. public static string ByteToString(byte[] arr)
  98. {
  99. try
  100. {
  101. return ByteToString(arr, true);
  102. }
  103. catch (Exception ex) { throw (ex); }
  104. }
  105. #endregion
  106.  
  107. #region StringToHexString
  108. public static string StringToHexString(string str)
  109. {
  110. StringBuilder s = new StringBuilder();
  111. foreach (short c in str.ToCharArray())
  112. {
  113. s.Append(c.ToString("X4"));
  114. }
  115. return s.ToString();
  116. }
  117. #endregion
  118.  
  119. #region StringToHexByte
  120. private static string ConvertChinese(string str)
  121. {
  122. StringBuilder s = new StringBuilder();
  123. foreach (short c in str.ToCharArray())
  124. {
  125. if (c <= 0 || c >= 127)
  126. {
  127. s.Append(c.ToString("X4"));
  128. }
  129. else
  130. {
  131. s.Append((char)c);
  132. }
  133. }
  134. return s.ToString();
  135. }
  136.  
  137. private static string FilterChinese(string str)
  138. {
  139. StringBuilder s = new StringBuilder();
  140. foreach (short c in str.ToCharArray())
  141. {
  142. if (c > 0 && c < 127)
  143. {
  144. s.Append((char)c);
  145. }
  146. }
  147. return s.ToString();
  148. }
  149.  
  150. /// <summary>
  151. /// 字符串转16进制字符数组
  152. /// </summary>
  153. /// <param name="hex"></param>
  154. /// <returns></returns>
  155. public static byte[] StringToHexByte(string str)
  156. {
  157. return StringToHexByte(str, false);
  158. }
  159.  
  160. /// <summary>
  161. /// 字符串转16进制字符数组
  162. /// </summary>
  163. /// <param name="str"></param>
  164. /// <param name="isFilterChinese">是否过滤掉中文字符</param>
  165. /// <returns></returns>
  166. public static byte[] StringToHexByte(string str, bool isFilterChinese)
  167. {
  168. string hex = isFilterChinese ? FilterChinese(str) : ConvertChinese(str);
  169.  
  170. //清除所有空格
  171. hex = hex.Replace(" ", "");
  172. //若字符个数为奇数,补一个0
  173. hex += hex.Length % 2 != 0 ? "0" : "";
  174.  
  175. byte[] result = new byte[hex.Length / 2];
  176. for (int i = 0, c = result.Length; i < c; i++)
  177. {
  178. result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
  179. }
  180. return result;
  181. }
  182. #endregion
  183.  
  184. }

调用示例:

CRC.ToCRC16("012345678",  true);          //结果为:C3CD
CRC.ToCRC16("012345678",  false);           //结果为:CDC3

CRC.ToModbusCRC16("012345678",  true);      //结果为:2801

CRC.ToCRC16("你好,我们测试一下CRC16算法",  true);   //结果为:0182

C#写的CRC16检验算法的更多相关文章

  1. JS写的CRC16校验算法

    var CRC = {}; CRC.CRC16 = function (data) { var len = data.length; if (len > 0) { var crc = 0xFFF ...

  2. JS写的CRC16校验算法(查表法)

    var CRC = {}; CRC._auchCRCHi = [ 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0 ...

  3. TensorFlow 入门之手写识别(MNIST) softmax算法

    TensorFlow 入门之手写识别(MNIST) softmax算法 MNIST flyu6 softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

  4. 『练手』手写一个独立Json算法 JsonHelper

    背景: > 一直使用 Newtonsoft.Json.dll 也算挺稳定的. > 但这个框架也挺闹心的: > 1.影响编译失败:https://www.cnblogs.com/zih ...

  5. BitSet: 有1千万个随机数,随机数的范围在1到1亿之间。现在要求写出一种算法,将1到1亿之间没有在随机数中的数求出来?

    package common; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import j ...

  6. Algorithm 用各种语言写出n!的算法

    写出n!的算法 C# 递归方式: class Program { static void Main(string[] args) { Console.WriteLine("请输入一个数!&q ...

  7. TensorFlow 入门之手写识别(MNIST) softmax算法 二

    TensorFlow 入门之手写识别(MNIST) softmax算法 二 MNIST Fly softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

  8. C++与JAVA代码实现CRC-16/MODBUS算法,且与 http://www.ip33.com/crc.html 进行结果验证

    CRC-16/MODBUS的多项式为:x16+x15+x2+1(8005),宽度为16.运算时,首先将一个16位的寄存器预置为11111111 11111111,然后连续把数据帧中的每个字节中的8位与 ...

  9. Python 手写数字识别-knn算法应用

    在上一篇博文中,我们对KNN算法思想及流程有了初步的了解,KNN是采用测量不同特征值之间的距离方法进行分类,也就是说对于每个样本数据,需要和训练集中的所有数据进行欧氏距离计算.这里简述KNN算法的特点 ...

随机推荐

  1. Nico Nico Ni~(完全背包)

    Time Limit:2000MS  Memory Limit:65535K Type: Program   Language: Not Limited Description Lys plays L ...

  2. ASP.NET 操作Cookie详解 增加,修改,删除

    Cookie,有时也用其复数形式Cookies,指某些网站为了辨别用户身份而储存在用户本地终端上的数据(通常经过加密).定义于RFC2109.它是网景公司的前雇员Lou Montulli在1993年3 ...

  3. 解决HttpServletResponse输出的中文乱码问题

    http://blog.csdn.net/simon_1/article/details/9092747 首先,response返回有两种,一种是字节流outputstream,一种是字符流print ...

  4. 纯CSS 实现tooltip 内容提示信息效果

    Tooltip 也就是内容的提示信息,合理使用可以给用户比较好的体验. 实现方法有很多种,有很多JS 插件,我这里介绍的是纯CSS实现的方法,兼容性也比较靠谱,IE8+均可正常显示.实现方法也非常简单 ...

  5. c++ 关于new文件

    new文件用来管理c++的动态内存,这个文件声明了几个全局空间的函数(不是std空间的函数,全局空间的函数调用时是用全局作用域解析符),包括operator new 和operator delete的 ...

  6. 转:关于垂直网格与CSS基线对其的探讨

    网页设计布局中一直比较流行网格对齐,但只是针对水平的对齐,很少或者没有涉及垂直对齐,这篇文章很详细的讲解了垂直网格,乃至基线对其的相关,而css3中的多列布局的也使其显得更为重要,因此还是很有必要去了 ...

  7. Xcode的command+shift+o是一个不错的工具

    一,经历 1.在向UITextField中输入图片的时候,可以使用 NSAttributedString 添加,但是很难找到能够返回NSAttributedString对象的方法. 2.通过comma ...

  8. 李洪强漫谈iOS开发[C语言]-045-循环结构

  9. ./*** > /dev/null 2>&1

    转载:http://dongwei.iteye.com/blog/322702 shell中可能经常能看到:>/dev/null 2>&1 命令的结果可以通过%>的形式来定义 ...

  10. oracle 连接查询,和(+)符号的用法

    --连接查询 左链接.右链接,全链接 --内链接select e.account 用户名, e.empname 名称, c.comname 公司名称  from employee e inner jo ...