Endian.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. namespace NModbus.Extensions.Functions
  2. {
  3. using System;
  4. /// <summary>
  5. /// Class containing functions to covert endian from network device to host this code is running on.
  6. /// </summary>
  7. public class Endian
  8. {
  9. /// <summary>
  10. /// Converts BigEndian source bytes to Endian format of system.
  11. /// Source BE: 0x0A,0x0B,0x0C,0x0D.
  12. /// Target BE: 0x0A,0x0B,0x0C,0x0D.
  13. /// Target LE: 0x0D,0x0C,0x0B,0x0A.
  14. /// </summary>
  15. /// <param name="sourceBytes">Byte array from device</param>
  16. /// <returns>Bytes in Endian format for system</returns>
  17. public static byte[] BigEndian(byte[] sourceBytes)
  18. {
  19. if (BitConverter.IsLittleEndian)
  20. {
  21. Array.Reverse(sourceBytes);
  22. }
  23. return sourceBytes;
  24. }
  25. /// <summary>
  26. /// Converts LittleEndian source bytes to Endian format of system.
  27. /// Source LE: 0x0D,0x0C,0x0B,0x0A.
  28. /// Target BE: 0x0A,0x0B,0x0C,0x0D.
  29. /// Target LE: 0x0D,0x0C,0x0B,0x0A.
  30. /// </summary>
  31. /// <param name="sourceBytes">Byte array from device</param>
  32. /// <returns>Bytes in Endian format for system</returns>
  33. public static byte[] LittleEndian(byte[] sourceBytes)
  34. {
  35. if (!BitConverter.IsLittleEndian)
  36. {
  37. Array.Reverse(sourceBytes);
  38. }
  39. return sourceBytes;
  40. }
  41. }
  42. }