Counter.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. namespace S7.Net.Types
  3. {
  4. /// <summary>
  5. /// Contains the conversion methods to convert Counter from S7 plc to C# ushort (UInt16).
  6. /// </summary>
  7. public static class Counter
  8. {
  9. /// <summary>
  10. /// Converts a Counter (2 bytes) to ushort (UInt16)
  11. /// </summary>
  12. public static UInt16 FromByteArray(byte[] bytes)
  13. {
  14. if (bytes.Length != 2)
  15. {
  16. throw new ArgumentException("Wrong number of bytes. Bytes array must contain 2 bytes.");
  17. }
  18. // bytes[0] -> HighByte
  19. // bytes[1] -> LowByte
  20. return (UInt16)((bytes[0] << 8) | bytes[1]);
  21. }
  22. /// <summary>
  23. /// Converts a ushort (UInt16) to word (2 bytes)
  24. /// </summary>
  25. public static byte[] ToByteArray(UInt16 value)
  26. {
  27. byte[] bytes = new byte[2];
  28. bytes[0] = (byte)((value << 8) & 0xFF);
  29. bytes[1] = (byte)((value) & 0xFF);
  30. return bytes;
  31. }
  32. /// <summary>
  33. /// Converts an array of ushort (UInt16) to an array of bytes
  34. /// </summary>
  35. public static byte[] ToByteArray(UInt16[] value)
  36. {
  37. ByteArray arr = new ByteArray();
  38. foreach (UInt16 val in value)
  39. arr.Add(ToByteArray(val));
  40. return arr.Array;
  41. }
  42. /// <summary>
  43. /// Converts an array of bytes to an array of ushort
  44. /// </summary>
  45. public static UInt16[] ToArray(byte[] bytes)
  46. {
  47. UInt16[] values = new UInt16[bytes.Length / 2];
  48. int counter = 0;
  49. for (int cnt = 0; cnt < bytes.Length / 2; cnt++)
  50. values[cnt] = FromByteArray(new byte[] { bytes[counter++], bytes[counter++] });
  51. return values;
  52. }
  53. }
  54. }