Real.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Real
  9. {
  10. /// <summary>
  11. /// Converts a S7 Real (4 bytes) to float
  12. /// </summary>
  13. public static float FromByteArray(byte[] bytes)
  14. {
  15. if (bytes.Length != 4)
  16. {
  17. throw new ArgumentException("Wrong number of bytes. Bytes array must contain 4 bytes.");
  18. }
  19. // sps uses bigending so we have to reverse if platform needs
  20. if (BitConverter.IsLittleEndian)
  21. {
  22. // create deep copy of the array and reverse
  23. bytes = new byte[] { bytes[3], bytes[2], bytes[1], bytes[0] };
  24. }
  25. return BitConverter.ToSingle(bytes, 0);
  26. }
  27. /// <summary>
  28. /// Converts a float to S7 Real (4 bytes)
  29. /// </summary>
  30. public static byte[] ToByteArray(float value)
  31. {
  32. byte[] bytes = BitConverter.GetBytes(value);
  33. // sps uses bigending so we have to check if platform is same
  34. if (!BitConverter.IsLittleEndian) return bytes;
  35. // create deep copy of the array and reverse
  36. return new byte[] { bytes[3], bytes[2], bytes[1], bytes[0] };
  37. }
  38. /// <summary>
  39. /// Converts an array of float to an array of bytes
  40. /// </summary>
  41. public static byte[] ToByteArray(float[] value)
  42. {
  43. var buffer = new byte[4 * value.Length];
  44. var stream = new MemoryStream(buffer);
  45. foreach (var val in value)
  46. {
  47. stream.Write(ToByteArray(val), 0, 4);
  48. }
  49. return buffer;
  50. }
  51. /// <summary>
  52. /// Converts an array of S7 Real to an array of float
  53. /// </summary>
  54. public static float[] ToArray(byte[] bytes)
  55. {
  56. var values = new float[bytes.Length / 4];
  57. int counter = 0;
  58. for (int cnt = 0; cnt < bytes.Length / 4; cnt++)
  59. values[cnt] = FromByteArray(new byte[] { bytes[counter++], bytes[counter++], bytes[counter++], bytes[counter++] });
  60. return values;
  61. }
  62. }
  63. }