Int.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. namespace S7.Net.Types
  3. {
  4. /// <summary>
  5. /// Contains the conversion methods to convert Int from S7 plc to C#.
  6. /// </summary>
  7. public static class Int
  8. {
  9. /// <summary>
  10. /// Converts a S7 Int (2 bytes) to short (Int16)
  11. /// </summary>
  12. public static short 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 (short)((int)(bytes[1]) | ((int)(bytes[0]) << 8));
  21. }
  22. /// <summary>
  23. /// Converts a short (Int16) to a S7 Int byte array (2 bytes)
  24. /// </summary>
  25. public static byte[] ToByteArray(Int16 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 short (Int16) to a S7 Int byte array (2 bytes)
  34. /// </summary>
  35. public static byte[] ToByteArray(Int16[] value)
  36. {
  37. byte[] bytes = new byte[value.Length * 2];
  38. int bytesPos = 0;
  39. for(int i=0; i< value.Length; i++)
  40. {
  41. bytes[bytesPos++] = (byte)((value[i] >> 8) & 0xFF);
  42. bytes[bytesPos++] = (byte) (value[i] & 0xFF);
  43. }
  44. return bytes;
  45. }
  46. /// <summary>
  47. /// Converts an array of S7 Int to an array of short (Int16)
  48. /// </summary>
  49. public static Int16[] ToArray(byte[] bytes)
  50. {
  51. int shortsCount = bytes.Length / 2;
  52. Int16[] values = new Int16[shortsCount];
  53. int counter = 0;
  54. for (int cnt = 0; cnt < shortsCount; cnt++)
  55. values[cnt] = FromByteArray(new byte[] { bytes[counter++], bytes[counter++] });
  56. return values;
  57. }
  58. /// <summary>
  59. /// Converts a C# int value to a C# short value, to be used as word.
  60. /// </summary>
  61. /// <param name="value"></param>
  62. /// <returns></returns>
  63. public static Int16 CWord(int value)
  64. {
  65. if (value > 32767)
  66. {
  67. value -= 32768;
  68. value = 32768 - value;
  69. value *= -1;
  70. }
  71. return (short)value;
  72. }
  73. }
  74. }