Timer.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. namespace S7.Net.Types
  3. {
  4. /// <summary>
  5. /// Converts the Timer data type to C# data type
  6. /// </summary>
  7. public static class Timer
  8. {
  9. /// <summary>
  10. /// Converts the timer bytes to a double
  11. /// </summary>
  12. public static double FromByteArray(byte[] bytes)
  13. {
  14. double wert = 0;
  15. wert = ((bytes[0]) & 0x0F) * 100.0;
  16. wert += ((bytes[1] >> 4) & 0x0F) * 10.0;
  17. wert += ((bytes[1]) & 0x0F) * 1.0;
  18. // this value is not used... may for a nother exponation
  19. //int unknown = (bytes[0] >> 6) & 0x03;
  20. switch ((bytes[0] >> 4) & 0x03)
  21. {
  22. case 0:
  23. wert *= 0.01;
  24. break;
  25. case 1:
  26. wert *= 0.1;
  27. break;
  28. case 2:
  29. wert *= 1.0;
  30. break;
  31. case 3:
  32. wert *= 10.0;
  33. break;
  34. }
  35. return wert;
  36. }
  37. /// <summary>
  38. /// Converts a ushort (UInt16) to an array of bytes formatted as time
  39. /// </summary>
  40. public static byte[] ToByteArray(UInt16 value)
  41. {
  42. byte[] bytes = new byte[2];
  43. bytes[1] = (byte)((int)value & 0xFF);
  44. bytes[0] = (byte)((int)value >> 8 & 0xFF);
  45. return bytes;
  46. }
  47. /// <summary>
  48. /// Converts an array of ushorts (Uint16) to an array of bytes formatted as time
  49. /// </summary>
  50. public static byte[] ToByteArray(UInt16[] value)
  51. {
  52. ByteArray arr = new ByteArray();
  53. foreach (UInt16 val in value)
  54. arr.Add(ToByteArray(val));
  55. return arr.Array;
  56. }
  57. /// <summary>
  58. /// Converts an array of bytes formatted as time to an array of doubles
  59. /// </summary>
  60. /// <param name="bytes"></param>
  61. /// <returns></returns>
  62. public static double[] ToArray(byte[] bytes)
  63. {
  64. double[] values = new double[bytes.Length / 2];
  65. int counter = 0;
  66. for (int cnt = 0; cnt < bytes.Length / 2; cnt++)
  67. values[cnt] = FromByteArray(new byte[] { bytes[counter++], bytes[counter++] });
  68. return values;
  69. }
  70. }
  71. }