LReal.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.IO;
  3. namespace S7.Net.Types
  4. {
  5. /// <summary>
  6. /// Contains the conversion methods to convert Real from S7 plc to C# double.
  7. /// </summary>
  8. public static class LReal
  9. {
  10. /// <summary>
  11. /// Converts a S7 LReal (8 bytes) to double
  12. /// </summary>
  13. public static double FromByteArray(byte[] bytes)
  14. {
  15. if (bytes.Length != 8)
  16. {
  17. throw new ArgumentException("Wrong number of bytes. Bytes array must contain 8 bytes.");
  18. }
  19. var buffer = bytes;
  20. // sps uses bigending so we have to reverse if platform needs
  21. if (BitConverter.IsLittleEndian)
  22. {
  23. Array.Reverse(buffer);
  24. }
  25. return BitConverter.ToDouble(buffer, 0);
  26. }
  27. /// <summary>
  28. /// Converts a double to S7 LReal (8 bytes)
  29. /// </summary>
  30. public static byte[] ToByteArray(double value)
  31. {
  32. var bytes = BitConverter.GetBytes(value);
  33. // sps uses bigending so we have to check if platform is same
  34. if (BitConverter.IsLittleEndian)
  35. {
  36. Array.Reverse(bytes);
  37. }
  38. return bytes;
  39. }
  40. /// <summary>
  41. /// Converts an array of double to an array of bytes
  42. /// </summary>
  43. public static byte[] ToByteArray(double[] value) => TypeHelper.ToByteArray(value, ToByteArray);
  44. /// <summary>
  45. /// Converts an array of S7 LReal to an array of double
  46. /// </summary>
  47. public static double[] ToArray(byte[] bytes) => TypeHelper.ToArray(bytes, FromByteArray);
  48. }
  49. }