ExtentionMethod.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace Edge.Core.Parser.BinaryParser.Util
  7. {
  8. public static class ExtentionMethod
  9. {
  10. /// <summary>
  11. /// string "123" convert to byte[0] 0000001, byte[1] 00100011
  12. /// </summary>
  13. /// <param name="value">int value</param>
  14. /// <returns></returns>
  15. public static byte[] ToBCD(this string value)
  16. {
  17. if (value.Length % 2 != 0)
  18. {
  19. value = "0" + value;
  20. }
  21. List<byte> result = new List<byte>();
  22. for (int i = 0; i < value.Length; i += 2)
  23. {
  24. int parsed = -1;
  25. try
  26. {
  27. parsed = int.Parse(value[i].ToString());
  28. }
  29. catch
  30. {
  31. throw new ArgumentException(value[i].ToString() + " in string: " + value + ", can't convert to int.");
  32. }
  33. byte b = (byte)(parsed << 4);
  34. if (i + 1 <= value.Length - 1)
  35. {
  36. try
  37. {
  38. parsed = int.Parse(value[i + 1].ToString());
  39. }
  40. catch
  41. {
  42. throw new ArgumentException(value[i + 1].ToString() + " in string: " + value + ", can't convert to int.");
  43. }
  44. b += (byte)parsed;
  45. }
  46. result.Add(b);
  47. }
  48. return result.ToArray();
  49. }
  50. /// <summary>
  51. /// convert bytes to a Hex format log String, each byte divided by a SPACE.
  52. /// byte[0] = 1, byte[1] = 15, byte[2] = 134, output 01 0F 86.
  53. /// </summary>
  54. /// <param name="bytes"></param>
  55. /// <returns></returns>
  56. public static string ToHexLogString(this IEnumerable<byte> bytes)
  57. {
  58. if (bytes == null)
  59. throw new ArgumentNullException("'bytes' argument for ToHexLogString must not be null");
  60. if (bytes.Any())
  61. return bytes.Select(s => s.ToString("X").PadLeft(2, '0')).Aggregate((acc, n) => acc + " " + n);
  62. else return "";
  63. }
  64. public static string ToHexLogString(this byte target)
  65. {
  66. return target.ToString("X").PadLeft(2, '0');
  67. }
  68. public static string ToHexLogString(this int value)
  69. {
  70. return BitConverter.GetBytes(value).Reverse().ToHexLogString();
  71. }
  72. /// <summary>
  73. /// Convert bytes to a BCD int value, e.g.: input byte[0]=00000110, byte[1]=00010001, output 611
  74. /// </summary>
  75. /// <param name="bytes"></param>
  76. /// <returns></returns>
  77. public static int GetBCD(this IEnumerable<byte> bytes)
  78. {
  79. if (bytes == null || !bytes.Any()) throw new ArgumentException("invalid bytes for BCD convert, it's null or empty");
  80. string final = bytes.Aggregate(string.Empty, (current, b) => current + b.GetBCDString());
  81. return int.Parse(final);
  82. }
  83. /// <summary>
  84. /// Convert bytes to a BCD int value, e.g.: input byte[0]=00000110, byte[1]=00010001, output 611
  85. /// </summary>
  86. /// <param name="bytes"></param>
  87. /// <returns></returns>
  88. public static long GetBcdLong(this IEnumerable<byte> bytes)
  89. {
  90. if (bytes == null || !bytes.Any()) throw new ArgumentException("invalid bytes for BCD convert, it's null or empty");
  91. string final = bytes.Aggregate(string.Empty, (current, b) => current + b.GetBCDString());
  92. return long.Parse(final);
  93. }
  94. /// <summary>
  95. /// Convert one byte to a BCD string, e.g.: input 00020001, output 21
  96. /// </summary>
  97. /// <param name="oneByte"></param>
  98. /// <returns></returns>
  99. public static int GetBCD(this byte oneByte)
  100. {
  101. int low = oneByte - (oneByte >> 4) * 16;
  102. int high = oneByte >> 4;
  103. if (high > 9 || low > 9) throw new ArgumentException("invalid BCD number conversion for raw byte: 0x" + oneByte.ToString("X").PadLeft(2, '0'));
  104. return low + high * 10;
  105. }
  106. /// <summary>
  107. /// Convert one byte to a BCD string, e.g.: input 00020001, output "21"
  108. /// </summary>
  109. /// <param name="oneByte">one byte need to be converted</param>
  110. /// <returns>string value stands for the BCD</returns>
  111. public static string GetBCDString(this byte oneByte)
  112. {
  113. return oneByte.GetBCD() < 10 ? oneByte.GetBCD().ToString().PadLeft(2, '0') : oneByte.GetBCD().ToString();
  114. }
  115. /// <summary>
  116. /// Convert a serial of bytes to a BCD string, e.g.: input [0]00110001 [1]00010100 [2]00020001, output "311421"
  117. /// </summary>
  118. /// <param name="oneByte">one byte need to be converted</param>
  119. /// <returns>string value stands for the BCD</returns>
  120. public static string GetBCDString(this byte[] targetBytes)
  121. {
  122. string result = "";
  123. for (int i = 0; i < targetBytes.Length; i++)
  124. {
  125. result += targetBytes[i].GetBCD() < 10 ? targetBytes[i].GetBCD().ToString().PadLeft(2, '0') : targetBytes[i].GetBCD().ToString();
  126. }
  127. return result;
  128. }
  129. /// <summary>
  130. /// Convert a bytes to a Int32 value, the byte element which has smaller index have the bigger power.
  131. /// like 2 length byte array: byte[0] = 1, byte[1] = 2, then the converted Int32 value is 0000000100000010 = 258
  132. /// </summary>
  133. /// <param name="targetBytes">input bytes</param>
  134. /// <returns>int32 value</returns>
  135. public static int ToInt32(this IEnumerable<byte> targetBytes)
  136. {
  137. int accu = 0;
  138. for (int i = 0; i < targetBytes.Count(); i++)
  139. {
  140. accu += targetBytes.ElementAt(i) << ((targetBytes.Count() - i - 1) * 8);
  141. }
  142. return accu;
  143. }
  144. /// <summary>
  145. /// Replace some bits in a byte. like 10 in decimal, unfold it to bit(right most is the bit 0): 00001010,
  146. /// now want to replace the from bit 1 to bit 3 to decimal 3 (unfold with 011), then the replaced value is 00000110 = 3.
  147. /// </summary>
  148. /// <param name="target">target byte</param>
  149. /// <param name="bitStartIndex">which bits to start, based on 0</param>
  150. /// <param name="bitEndIndex">replace to which bits, based on 0</param>
  151. /// <param name="replacedValue">value which replaced to</param>
  152. /// <returns>the replaced value</returns>
  153. public static byte SetBit(this byte target, int bitStartIndex, int bitEndIndex, int replacedValue)
  154. {
  155. if (bitStartIndex < 0 || bitEndIndex > 7 || bitEndIndex < bitStartIndex)
  156. {
  157. throw new ArgumentException("bitStartIndex or bitEndIndex value is not valid");
  158. }
  159. byte mask = 0;
  160. for (int i = 0; i < bitEndIndex - bitStartIndex + 1; i++)
  161. {
  162. mask += (byte)Math.Pow(2, i);
  163. }
  164. if (replacedValue > mask)
  165. {
  166. throw new ArgumentOutOfRangeException("Replaced value: " + replacedValue + " cannot fit the bits range");
  167. }
  168. byte maskedValue = (byte)(target & (255 - (mask << bitStartIndex)));
  169. return (byte)(maskedValue + (replacedValue << bitStartIndex));
  170. }
  171. /// <summary>
  172. /// Like int 28, interpreted as binary 00011100, so index 0 bit is 0, index 2 bit is 1, index 3 bit is 1,
  173. /// index 4 bit is 1, index 5 bit is 0.
  174. /// </summary>
  175. /// <param name="target"></param>
  176. /// <param name="index">from low to high digits, based on 0.</param>
  177. /// <returns></returns>
  178. public static byte GetBit(this byte target, int index)
  179. {
  180. if (index < 0 || index > 7)
  181. {
  182. throw new ArgumentException("index value is not valid");
  183. }
  184. var turn = (target >> (index));
  185. var t = (turn << 7).GetBinBytes(4).Last() >> 7;
  186. return (byte)t;
  187. }
  188. /// <summary>
  189. /// Convert a hex string to a byte[]
  190. /// like targetHexString is 01030E, then the result bytes is: byte[0] = 1, byte[1] = 3, byte [2] = 14.
  191. /// </summary>
  192. /// <param name="targetHexString">input hex string</param>
  193. /// <returns>byte[]</returns>
  194. public static byte[] ToBytes(this string targetHexString)
  195. {
  196. targetHexString = targetHexString.Trim().Replace(" ", "");
  197. if (targetHexString.Length % 2 != 0)
  198. {
  199. throw new ArgumentException("The targetHexString length is not even.");
  200. }
  201. List<byte> result = new List<byte>();
  202. for (int i = 0; i < targetHexString.Length; i += 2)
  203. {
  204. var middle = targetHexString.Substring(i, 2);
  205. result.Add(Convert.ToByte(middle, 16));
  206. }
  207. return result.ToArray();
  208. }
  209. /// <summary>
  210. /// Append a bytes to the head of base bytes, like base bytes is byte[0] = 0, byte[1]=1, appending bytes is byte[0] = 2, then the result
  211. /// is byte[0] = 2, byte[1] = 0, byte[2] = 1.
  212. /// </summary>
  213. /// <param name="baseBytes"></param>
  214. /// <param name="bytesToAppending"></param>
  215. /// <returns></returns>
  216. public static byte[] AppendToHeader(this byte[] baseBytes, byte[] bytesToAppending)
  217. {
  218. return bytesToAppending.Concat(baseBytes).ToArray();
  219. }
  220. /// <summary>
  221. /// Convert a int to a bytes with BCD encoding, like 13(with outputtotalBytes set to 4)
  222. /// convert to byte[0] = 00000000, byte[1] = 00010011
  223. /// </summary>
  224. /// <param name="targetInt">target int value</param>
  225. /// <param name="outputTotalBytes">the array length of the output, put <![CDATA[<=]>]]>0 as the auto detect length</param>
  226. /// <returns>bytes</returns>
  227. public static byte[] GetBCDBytes(this long targetInt, int outputTotalBytes)
  228. {
  229. // put each digit to a single byte, like int 134 put into byte[0] = 00000000, byte[1] = 00000011, byte[2] = 00000100
  230. var process = targetInt.ToString().Select(b => (byte)int.Parse(b.ToString())).ToList();
  231. // always extend to even
  232. if (process.Count() % 2 != 0)
  233. {
  234. process = process.ToArray().AppendToHeader(new byte[] { 0 }).ToList();
  235. }
  236. // left move 4 bit for odd index item, then plus the followed even index item, form one byte of BCD.
  237. // then remove that odd index item.
  238. for (int i = process.Count() - 1; i >= 0; i--)
  239. {
  240. process[i] += (byte)(process.ToArray()[i - 1] << 4);
  241. process.RemoveAt(i - 1);
  242. i = i - 1;
  243. }
  244. var diff = outputTotalBytes - process.Count;
  245. if (diff > 0)
  246. {
  247. var v = Enumerable.Repeat(0, diff).Select(p => (byte)p).Concat(process).ToArray();
  248. return v;
  249. }
  250. return process.ToArray();
  251. }
  252. public static byte[] GetBCDBytes(this System.Numerics.BigInteger targetInt, int outputTotalBytes)
  253. {
  254. // put each digit to a single byte, like int 134 put into byte[0] = 00000000, byte[1] = 00000011, byte[2] = 00000100
  255. var process = targetInt.ToString().Select(b => (byte)int.Parse(b.ToString())).ToList();
  256. // always extend to even
  257. if (process.Count() % 2 != 0)
  258. {
  259. process = process.ToArray().AppendToHeader(new byte[] { 0 }).ToList();
  260. }
  261. // left move 4 bit for odd index item, then plus the followed even index item, form one byte of BCD.
  262. // then remove that odd index item.
  263. for (int i = process.Count() - 1; i >= 0; i--)
  264. {
  265. process[i] += (byte)(process.ToArray()[i - 1] << 4);
  266. process.RemoveAt(i - 1);
  267. i = i - 1;
  268. }
  269. var diff = outputTotalBytes - process.Count;
  270. if (diff > 0)
  271. {
  272. var v = Enumerable.Repeat(0, diff).Select(p => (byte)p).Concat(process).ToArray();
  273. return v;
  274. }
  275. return process.ToArray();
  276. }
  277. public static byte[] GetBCDBytes(this int targetInt, int outputTotalBytes)
  278. {
  279. // put each digit to a single byte, like int 134 put into byte[0] = 00000000, byte[1] = 00000011, byte[2] = 00000100
  280. var process = targetInt.ToString().Select(b => (byte)int.Parse(b.ToString())).ToList();
  281. // always extend to even
  282. if (process.Count() % 2 != 0)
  283. {
  284. process = process.ToArray().AppendToHeader(new byte[] { 0 }).ToList();
  285. }
  286. // left move 4 bit for odd index item, then plus the followed even index item, form one byte of BCD.
  287. // then remove that odd index item.
  288. for (int i = process.Count() - 1; i >= 0; i--)
  289. {
  290. process[i] += (byte)(process.ToArray()[i - 1] << 4);
  291. process.RemoveAt(i - 1);
  292. i = i - 1;
  293. }
  294. var diff = outputTotalBytes - process.Count;
  295. if (diff > 0)
  296. {
  297. var v = Enumerable.Repeat(0, diff).Select(p => (byte)p).Concat(process).ToArray();
  298. return v;
  299. }
  300. return process.ToArray();
  301. }
  302. /// <summary>
  303. /// Convert a int value to a bytes,
  304. /// low byte have the high order.
  305. /// like 3 convert to byte[0] = 00000011;
  306. /// 256 convert to byte[0] = 00000001, byte[1] = 00000000;
  307. /// 257 conver to byte[0] = 00000001, byte[1] = 0000001;
  308. /// 8800 conver to byte[0] = 00100010, byte[1] = 01100000;
  309. /// </summary>
  310. /// <param name="targetInt">target int value</param>
  311. /// <param name="outputTotalBytes">the array length of the output, put <![CDATA[<=]>]]>0 as the auto detect length</param>
  312. /// <returns>bytes</returns>
  313. public static byte[] GetBinBytes(this int targetInt, int outputTotalBytes)
  314. {
  315. if (outputTotalBytes > 4) throw new ArgumentOutOfRangeException("GetBinBytes support max 4 bytes output");
  316. var r = BitConverter.GetBytes(targetInt);
  317. if (outputTotalBytes == 0) return r;
  318. if (outputTotalBytes < r.Length)
  319. {
  320. for (int index = r.Length - 1; index > outputTotalBytes - 1; index--)
  321. {
  322. if (r[index] > 0)
  323. {
  324. throw new ArgumentException(string.Format("Target integer value {0} is too large to be converted into {1} bytes", targetInt, outputTotalBytes));
  325. }
  326. }
  327. }
  328. if (outputTotalBytes > 0)
  329. {
  330. return r.Take(outputTotalBytes).Reverse().ToArray();
  331. }
  332. return r.Reverse().ToArray();
  333. }
  334. public static byte[] GetBinBytes(this long targetInt, int outputTotalBytes)
  335. {
  336. if (outputTotalBytes > 4) throw new ArgumentOutOfRangeException("GetBinBytes support max 4 bytes output");
  337. var r = BitConverter.GetBytes(targetInt);
  338. if (outputTotalBytes == 0) return r;
  339. if (outputTotalBytes < r.Length)
  340. {
  341. for (int index = r.Length - 1; index > outputTotalBytes - 1; index--)
  342. {
  343. if (r[index] > 0)
  344. {
  345. throw new ArgumentException(string.Format("Target integer value {0} is too large to be converted into {1} bytes", targetInt, outputTotalBytes));
  346. }
  347. }
  348. }
  349. if (outputTotalBytes > 0)
  350. {
  351. return r.Take(outputTotalBytes).Reverse().ToArray();
  352. }
  353. return r.Reverse().ToArray();
  354. }
  355. /// <summary>
  356. /// Convert a bytes array to a string with hex encoding, like a byte[] { 00, 00, 64, 04 }, then converted string will be 00004004
  357. /// </summary>
  358. /// <param name="target">target byte array</param>
  359. /// <returns>a string with hex encoding</returns>
  360. public static string GetHexString(this IEnumerable<byte> target)
  361. {
  362. return target.Select(b => b.ToString("X").Length == 1 ? b.ToString("X").PadLeft(2, '0') : b.ToString("X")).Aggregate((p, n) => { return p + n; });
  363. }
  364. public static bool ValueEquals(this IEnumerable<byte> array1, IEnumerable<byte> array2)
  365. {
  366. if (array1 == null && array2 == null)
  367. {
  368. return true;
  369. }
  370. if ((array1 == null) || (array2 == null))
  371. {
  372. return false;
  373. }
  374. if (array1.Count() != array2.Count())
  375. {
  376. return false;
  377. }
  378. if (array1.Equals(array2))
  379. {
  380. return true;
  381. }
  382. else
  383. {
  384. for (int Index = 0; Index < array1.Count(); Index++)
  385. {
  386. if (!Equals(array1.ElementAt(Index), array2.ElementAt(Index)))
  387. {
  388. return false;
  389. }
  390. }
  391. }
  392. return true;
  393. }
  394. /// <summary>
  395. /// Get the first or default element in a WinEps message which specified by the element type.
  396. /// Since the element is a reference type, so nothing find will return a Null as the default value.
  397. /// </summary>
  398. /// <typeparam name="T">the look up element type</typeparam>
  399. /// <param name="message">WinEps message</param>
  400. /// <returns>the element, if not found, return null</returns>
  401. //public static T FirstOrDefaultElement<T>(this WinEpsMessageBase message) where T : WinEpsElementBase
  402. //{
  403. // return message.FirstOrDefault(e => e.GetType() == typeof(T)) as T;
  404. //}
  405. //private static ushort[] table = {
  406. // 0x0000, 0x1189, 0x2312, 0x329B, 0x4624, 0x57AD, 0x6536, 0x74BF,
  407. // 0x8C48, 0x9DC1, 0xAF5A, 0xBED3, 0xCA6C, 0xDBE5, 0xE97E, 0xF8F7,
  408. // 0x1081, 0x0108, 0x3393, 0x221A, 0x56A5, 0x472C, 0x75B7, 0x643E,
  409. // 0x9CC9, 0x8D40, 0xBFDB, 0xAE52, 0xDAED, 0xCB64, 0xF9FF, 0xE876,
  410. // 0x2102, 0x308B, 0x0210, 0x1399, 0x6726, 0x76AF, 0x4434, 0x55BD,
  411. // 0xAD4A, 0xBCC3, 0x8E58, 0x9FD1, 0xEB6E, 0xFAE7, 0xC87C, 0xD9F5,
  412. // 0x3183, 0x200A, 0x1291, 0x0318, 0x77A7, 0x662E, 0x54B5, 0x453C,
  413. // 0xBDCB, 0xAC42, 0x9ED9, 0x8F50, 0xFBEF, 0xEA66, 0xD8FD, 0xC974,
  414. // 0x4204, 0x538D, 0x6116, 0x709F, 0x0420, 0x15A9, 0x2732, 0x36BB,
  415. // 0xCE4C, 0xDFC5, 0xED5E, 0xFCD7, 0x8868, 0x99E1, 0xAB7A, 0xBAF3,
  416. // 0x5285, 0x430C, 0x7197, 0x601E, 0x14A1, 0x0528, 0x37B3, 0x263A,
  417. // 0xDECD, 0xCF44, 0xFDDF, 0xEC56, 0x98E9, 0x8960, 0xBBFB, 0xAA72,
  418. // 0x6306, 0x728F, 0x4014, 0x519D, 0x2522, 0x34AB, 0x0630, 0x17B9,
  419. // 0xEF4E, 0xFEC7, 0xCC5C, 0xDDD5, 0xA96A, 0xB8E3, 0x8A78, 0x9BF1,
  420. // 0x7387, 0x620E, 0x5095, 0x411C, 0x35A3, 0x242A, 0x16B1, 0x0738,
  421. // 0xFFCF, 0xEE46, 0xDCDD, 0xCD54, 0xB9EB, 0xA862, 0x9AF9, 0x8B70,
  422. // 0x8408, 0x9581, 0xA71A, 0xB693, 0xC22C, 0xD3A5, 0xE13E, 0xF0B7,
  423. // 0x0840, 0x19C9, 0x2B52, 0x3ADB, 0x4E64, 0x5FED, 0x6D76, 0x7CFF,
  424. // 0x9489, 0x8500, 0xB79B, 0xA612, 0xD2AD, 0xC324, 0xF1BF, 0xE036,
  425. // 0x18C1, 0x0948, 0x3BD3, 0x2A5A, 0x5EE5, 0x4F6C, 0x7DF7, 0x6C7E,
  426. // 0xA50A, 0xB483, 0x8618, 0x9791, 0xE32E, 0xF2A7, 0xC03C, 0xD1B5,
  427. // 0x2942, 0x38CB, 0x0A50, 0x1BD9, 0x6F66, 0x7EEF, 0x4C74, 0x5DFD,
  428. // 0xB58B, 0xA402, 0x9699, 0x8710, 0xF3AF, 0xE226, 0xD0BD, 0xC134,
  429. // 0x39C3, 0x284A, 0x1AD1, 0x0B58, 0x7FE7, 0x6E6E, 0x5CF5, 0x4D7C,
  430. // 0xC60C, 0xD785, 0xE51E, 0xF497, 0x8028, 0x91A1, 0xA33A, 0xB2B3,
  431. // 0x4A44, 0x5BCD, 0x6956, 0x78DF, 0x0C60, 0x1DE9, 0x2F72, 0x3EFB,
  432. // 0xD68D, 0xC704, 0xF59F, 0xE416, 0x90A9, 0x8120, 0xB3BB, 0xA232,
  433. // 0x5AC5, 0x4B4C, 0x79D7, 0x685E, 0x1CE1, 0x0D68, 0x3FF3, 0x2E7A,
  434. // 0xE70E, 0xF687, 0xC41C, 0xD595, 0xA12A, 0xB0A3, 0x8238, 0x93B1,
  435. // 0x6B46, 0x7ACF, 0x4854, 0x59DD, 0x2D62, 0x3CEB, 0x0E70, 0x1FF9,
  436. // 0xF78F, 0xE606, 0xD49D, 0xC514, 0xB1AB, 0xA022, 0x92B9, 0x8330,
  437. // 0x7BC7, 0x6A4E, 0x58D5, 0x495C, 0x3DE3, 0x2C6A, 0x1EF1, 0x0F78
  438. // };
  439. static ushort[] table = new ushort[256];
  440. const ushort polynomial = 0xA001;
  441. private static ushort ComputeChecksum(byte[] bytes)
  442. {
  443. ushort crc = 0;
  444. for (int i = 0; i < bytes.Length; ++i)
  445. {
  446. byte index = (byte)(crc ^ bytes[i]);
  447. crc = (ushort)((crc >> 8) ^ table[index]);
  448. }
  449. return crc;
  450. }
  451. public static byte[] ComputeChecksumBytesCrc16(this byte[] bytes)
  452. {
  453. ushort crc = ComputeChecksum(bytes);
  454. var result = BitConverter.GetBytes(crc);
  455. return result.Reverse().ToArray();
  456. }
  457. private static ushort ComputeChecksumModBus(byte[] bytes)
  458. {
  459. ushort crc = 0xFFFF;
  460. for (int i = 0; i < bytes.Length; ++i)
  461. {
  462. byte index = (byte)(crc ^ bytes[i]);
  463. crc = (ushort)((crc >> 8) ^ table[index]);
  464. }
  465. return crc;
  466. }
  467. public static byte[] ComputeChecksumBytesCrc16ModBus(this byte[] bytes)
  468. {
  469. ushort crc = ComputeChecksumModBus(bytes);
  470. var result = BitConverter.GetBytes(crc);
  471. return result.Reverse().ToArray();
  472. }
  473. private static readonly ushort[] CrcTable =
  474. {
  475. 0X0000, 0XC0C1, 0XC181, 0X0140, 0XC301, 0X03C0, 0X0280, 0XC241,
  476. 0XC601, 0X06C0, 0X0780, 0XC741, 0X0500, 0XC5C1, 0XC481, 0X0440,
  477. 0XCC01, 0X0CC0, 0X0D80, 0XCD41, 0X0F00, 0XCFC1, 0XCE81, 0X0E40,
  478. 0X0A00, 0XCAC1, 0XCB81, 0X0B40, 0XC901, 0X09C0, 0X0880, 0XC841,
  479. 0XD801, 0X18C0, 0X1980, 0XD941, 0X1B00, 0XDBC1, 0XDA81, 0X1A40,
  480. 0X1E00, 0XDEC1, 0XDF81, 0X1F40, 0XDD01, 0X1DC0, 0X1C80, 0XDC41,
  481. 0X1400, 0XD4C1, 0XD581, 0X1540, 0XD701, 0X17C0, 0X1680, 0XD641,
  482. 0XD201, 0X12C0, 0X1380, 0XD341, 0X1100, 0XD1C1, 0XD081, 0X1040,
  483. 0XF001, 0X30C0, 0X3180, 0XF141, 0X3300, 0XF3C1, 0XF281, 0X3240,
  484. 0X3600, 0XF6C1, 0XF781, 0X3740, 0XF501, 0X35C0, 0X3480, 0XF441,
  485. 0X3C00, 0XFCC1, 0XFD81, 0X3D40, 0XFF01, 0X3FC0, 0X3E80, 0XFE41,
  486. 0XFA01, 0X3AC0, 0X3B80, 0XFB41, 0X3900, 0XF9C1, 0XF881, 0X3840,
  487. 0X2800, 0XE8C1, 0XE981, 0X2940, 0XEB01, 0X2BC0, 0X2A80, 0XEA41,
  488. 0XEE01, 0X2EC0, 0X2F80, 0XEF41, 0X2D00, 0XEDC1, 0XEC81, 0X2C40,
  489. 0XE401, 0X24C0, 0X2580, 0XE541, 0X2700, 0XE7C1, 0XE681, 0X2640,
  490. 0X2200, 0XE2C1, 0XE381, 0X2340, 0XE101, 0X21C0, 0X2080, 0XE041,
  491. 0XA001, 0X60C0, 0X6180, 0XA141, 0X6300, 0XA3C1, 0XA281, 0X6240,
  492. 0X6600, 0XA6C1, 0XA781, 0X6740, 0XA501, 0X65C0, 0X6480, 0XA441,
  493. 0X6C00, 0XACC1, 0XAD81, 0X6D40, 0XAF01, 0X6FC0, 0X6E80, 0XAE41,
  494. 0XAA01, 0X6AC0, 0X6B80, 0XAB41, 0X6900, 0XA9C1, 0XA881, 0X6840,
  495. 0X7800, 0XB8C1, 0XB981, 0X7940, 0XBB01, 0X7BC0, 0X7A80, 0XBA41,
  496. 0XBE01, 0X7EC0, 0X7F80, 0XBF41, 0X7D00, 0XBDC1, 0XBC81, 0X7C40,
  497. 0XB401, 0X74C0, 0X7580, 0XB541, 0X7700, 0XB7C1, 0XB681, 0X7640,
  498. 0X7200, 0XB2C1, 0XB381, 0X7340, 0XB101, 0X71C0, 0X7080, 0XB041,
  499. 0X5000, 0X90C1, 0X9181, 0X5140, 0X9301, 0X53C0, 0X5280, 0X9241,
  500. 0X9601, 0X56C0, 0X5780, 0X9741, 0X5500, 0X95C1, 0X9481, 0X5440,
  501. 0X9C01, 0X5CC0, 0X5D80, 0X9D41, 0X5F00, 0X9FC1, 0X9E81, 0X5E40,
  502. 0X5A00, 0X9AC1, 0X9B81, 0X5B40, 0X9901, 0X59C0, 0X5880, 0X9841,
  503. 0X8801, 0X48C0, 0X4980, 0X8941, 0X4B00, 0X8BC1, 0X8A81, 0X4A40,
  504. 0X4E00, 0X8EC1, 0X8F81, 0X4F40, 0X8D01, 0X4DC0, 0X4C80, 0X8C41,
  505. 0X4400, 0X84C1, 0X8581, 0X4540, 0X8701, 0X47C0, 0X4680, 0X8641,
  506. 0X8201, 0X42C0, 0X4380, 0X8341, 0X4100, 0X81C1, 0X8081, 0X4040
  507. };
  508. public static byte[] CalculateModBusCrc(this byte[] data)
  509. {
  510. if (data == null)
  511. {
  512. throw new ArgumentNullException(nameof(data));
  513. }
  514. ushort crc = ushort.MaxValue;
  515. foreach (byte b in data)
  516. {
  517. byte tableIndex = (byte)(crc ^ b);
  518. crc >>= 8;
  519. crc ^= CrcTable[tableIndex];
  520. }
  521. return BitConverter.GetBytes(crc);
  522. }
  523. public static byte CalculateLRC(this IEnumerable<byte> bytes)
  524. {
  525. int LRC = 0;
  526. for (int i = 0; i < bytes.Count(); i++)
  527. {
  528. LRC ^= bytes.ElementAt(i);
  529. }
  530. return (byte)LRC;
  531. }
  532. static ExtentionMethod()
  533. {
  534. ushort value;
  535. ushort temp;
  536. for (ushort i = 0; i < table.Length; ++i)
  537. {
  538. value = 0;
  539. temp = i;
  540. for (byte j = 0; j < 8; ++j)
  541. {
  542. if (((value ^ temp) & 0x0001) != 0)
  543. {
  544. value = (ushort)((value >> 1) ^ polynomial);
  545. }
  546. else
  547. {
  548. value >>= 1;
  549. }
  550. temp >>= 1;
  551. }
  552. table[i] = value;
  553. }
  554. }
  555. }
  556. //public class Crc16
  557. //{
  558. // const ushort polynomial = 0xA001;
  559. // ushort[] table = new ushort[256];
  560. // public ushort ComputeChecksum(byte[] bytes)
  561. // {
  562. // ushort crc = 0;
  563. // for (int i = 0; i < bytes.Length; ++i)
  564. // {
  565. // byte index = (byte)(crc ^ bytes[i]);
  566. // crc = (ushort)((crc >> 8) ^ table[index]);
  567. // }
  568. // return crc;
  569. // }
  570. // public byte[] ComputeChecksumBytesCrc16(byte[] bytes)
  571. // {
  572. // ushort crc = ComputeChecksum(bytes);
  573. // return BitConverter.GetBytes(crc);
  574. // }
  575. // public Crc16()
  576. // {
  577. // ushort value;
  578. // ushort temp;
  579. // for (ushort i = 0; i < table.Length; ++i)
  580. // {
  581. // value = 0;
  582. // temp = i;
  583. // for (byte j = 0; j < 8; ++j)
  584. // {
  585. // if (((value ^ temp) & 0x0001) != 0)
  586. // {
  587. // value = (ushort)((value >> 1) ^ polynomial);
  588. // }
  589. // else
  590. // {
  591. // value >>= 1;
  592. // }
  593. // temp >>= 1;
  594. // }
  595. // table[i] = value;
  596. // }
  597. // }
  598. //}
  599. }