DWord.cs 2.0 KB

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