Extensions.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.ComponentModel;
  3. using System.Reflection;
  4. namespace WayneChina_IcCardReader_SinoChem
  5. {
  6. public static class Extensions
  7. {
  8. public static void SetPropertyValue(this object target, string propertyName, string propertyValue)
  9. {
  10. PropertyInfo propInfo = target.GetType().GetProperty(propertyName);
  11. Type propType = propInfo.PropertyType;
  12. if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
  13. {
  14. if (propertyValue == null)
  15. {
  16. propInfo.SetValue(target, null, null);
  17. return;
  18. }
  19. propType = new NullableConverter(propInfo.PropertyType).UnderlyingType;
  20. }
  21. propInfo.SetValue(target, Convert.ChangeType(propertyValue, propType), null);
  22. }
  23. public static byte[] Crc16Ccitt(this byte[] bytes)
  24. {
  25. const ushort poly = 4129;
  26. ushort[] table = new ushort[256];
  27. ushort initialValue = 0xFFFF;
  28. ushort temp, a;
  29. ushort crc = initialValue;
  30. for (int i = 0; i < table.Length; ++i)
  31. {
  32. temp = 0;
  33. a = (ushort)(i << 8);
  34. for (int j = 0; j < 8; ++j)
  35. {
  36. if (((temp ^ a) & 0x8000) != 0)
  37. temp = (ushort)((temp << 1) ^ poly);
  38. else
  39. temp <<= 1;
  40. a <<= 1;
  41. }
  42. table[i] = temp;
  43. }
  44. for (int i = 0; i < bytes.Length; ++i)
  45. {
  46. crc = (ushort)((crc << 8) ^ table[((crc >> 8) ^ (0xFF & bytes[i]))]);
  47. }
  48. return BitConverter.GetBytes(crc);
  49. }
  50. }
  51. }