UnionHelper.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System.Runtime.InteropServices;
  2. namespace Universal;
  3. public class UnionHelper
  4. {
  5. public static void GetByteUnion(byte input, out bool[] bits)
  6. {
  7. bits = new bool[8];
  8. for (int i = 0; i < 8; i++)
  9. bits[i] = Convert.ToBoolean((input >> i) & 0b01);
  10. }
  11. public static void GetByteUnion(byte input, out byte[] bits)
  12. {
  13. bits = new byte[8];
  14. for (int i = 0; i < 8; i++)
  15. bits[i] = (byte)((input >> i) & 0b01);
  16. }
  17. }
  18. public class StructHelper
  19. {
  20. public static byte[] StructToBytes<T>(T structObj) where T : struct
  21. {
  22. int size = Marshal.SizeOf(structObj);
  23. IntPtr buffer = Marshal.AllocHGlobal(size);
  24. try
  25. {
  26. Marshal.StructureToPtr(structObj, buffer, false);
  27. byte[] bytes = new byte[size];
  28. Marshal.Copy(buffer, bytes, 0, size);
  29. return bytes;
  30. }
  31. finally
  32. {
  33. Marshal.FreeHGlobal(buffer);
  34. }
  35. }
  36. public static T BytesToStruct<T>(byte[] bytes) where T : struct
  37. {
  38. int size = Marshal.SizeOf<T>();
  39. IntPtr buffer = Marshal.AllocHGlobal(size);
  40. try
  41. {
  42. Marshal.Copy(bytes, 0, buffer, size);
  43. return Marshal.PtrToStructure<T>(buffer);
  44. }
  45. finally
  46. {
  47. Marshal.FreeHGlobal(buffer);
  48. }
  49. }
  50. public static byte[] Ushorts2Bytes(ushort[] src, bool reverse = false)
  51. {
  52. int count = src.Length;
  53. byte[] dest = new byte[count << 1];
  54. if (reverse)
  55. {
  56. for (int i = 0; i < count; i++)
  57. {
  58. dest[i * 2] = (byte)(src[i] >> 8);
  59. dest[i * 2 + 1] = (byte)(src[i] >> 0);
  60. }
  61. }
  62. else
  63. {
  64. for (int i = 0; i < count; i++)
  65. {
  66. dest[i * 2] = (byte)(src[i] >> 0);
  67. dest[i * 2 + 1] = (byte)(src[i] >> 8);
  68. }
  69. }
  70. return dest;
  71. }
  72. public static ushort[] Bytes2Ushorts(byte[] src, bool reverse = false)
  73. {
  74. int len = src.Length;
  75. byte[] srcPlus = new byte[len + 1];
  76. src.CopyTo(srcPlus, 0);
  77. int count = len >> 1;
  78. if (len % 2 != 0)
  79. {
  80. count += 1;
  81. }
  82. ushort[] dest = new ushort[count];
  83. if (reverse)
  84. {
  85. for (int i = 0; i < count; i++)
  86. {
  87. dest[i] = (ushort)(srcPlus[i * 2] << 8 | srcPlus[2 * i + 1] & 0xff);
  88. }
  89. }
  90. else
  91. {
  92. for (int i = 0; i < count; i++)
  93. {
  94. dest[i] = (ushort)(srcPlus[i * 2] & 0xff | srcPlus[2 * i + 1] << 8);
  95. }
  96. }
  97. return dest;
  98. }
  99. }