DInt.cs 1.9 KB

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