Word.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. namespace S7.Net.Types
  3. {
  4. /// <summary>
  5. /// Contains the conversion methods to convert Words from S7 plc to C#.
  6. /// </summary>
  7. public static class Word
  8. {
  9. /// <summary>
  10. /// Converts a word (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. return (UInt16)((bytes[0] << 8) | bytes[1]);
  19. }
  20. /// <summary>
  21. /// Converts 2 bytes to ushort (UInt16)
  22. /// </summary>
  23. public static UInt16 FromBytes(byte b1, byte b2)
  24. {
  25. return (UInt16)((b2 << 8) | b1);
  26. }
  27. /// <summary>
  28. /// Converts a ushort (UInt16) to word (2 bytes)
  29. /// </summary>
  30. public static byte[] ToByteArray(UInt16 value)
  31. {
  32. byte[] bytes = new byte[2];
  33. bytes[1] = (byte)(value & 0xFF);
  34. bytes[0] = (byte)((value>>8) & 0xFF);
  35. return bytes;
  36. }
  37. /// <summary>
  38. /// Converts an array of ushort (UInt16) to an array of bytes
  39. /// </summary>
  40. public static byte[] ToByteArray(UInt16[] value)
  41. {
  42. ByteArray arr = new ByteArray();
  43. foreach (UInt16 val in value)
  44. arr.Add(ToByteArray(val));
  45. return arr.Array;
  46. }
  47. /// <summary>
  48. /// Converts an array of bytes to an array of ushort
  49. /// </summary>
  50. public static UInt16[] ToArray(byte[] bytes)
  51. {
  52. UInt16[] values = new UInt16[bytes.Length/2];
  53. int counter = 0;
  54. for (int cnt = 0; cnt < bytes.Length/2; cnt++)
  55. values[cnt] = FromByteArray(new byte[] {bytes[counter++], bytes[counter++]});
  56. return values;
  57. }
  58. }
  59. }