Endian.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace CarLocalMeter
  7. {
  8. /// <summary>
  9. /// 字节序转换
  10. /// </summary>
  11. public static class Endian
  12. {
  13. public static short SwapInt16(this short n)
  14. {
  15. return (short)(((n & 0xff) << 8) | ((n >> 8) & 0xff));
  16. }
  17. public static ushort SwapUInt16(this ushort n)
  18. {
  19. return (ushort)(((n & 0xff) << 8) | ((n >> 8) & 0xff));
  20. }
  21. public static int SwapInt32(this int n)
  22. {
  23. return (int)(((SwapInt16((short)n) & 0xffff) << 0x10) |
  24. (SwapInt16((short)(n >> 0x10)) & 0xffff));
  25. }
  26. public static uint SwapUInt32(this uint n)
  27. {
  28. return (uint)(((SwapUInt16((ushort)n) & 0xffff) << 0x10) |
  29. (SwapUInt16((ushort)(n >> 0x10)) & 0xffff));
  30. }
  31. public static long SwapInt64(this long n)
  32. {
  33. return (long)(((SwapInt32((int)n) & 0xffffffffL) << 0x20) |
  34. (SwapInt32((int)(n >> 0x20)) & 0xffffffffL));
  35. }
  36. public static ulong SwapUInt64(this ulong n)
  37. {
  38. return (ulong)(((SwapUInt32((uint)n) & 0xffffffffL) << 0x20) |
  39. (SwapUInt32((uint)(n >> 0x20)) & 0xffffffffL));
  40. }
  41. }
  42. }