UnionHelper.cs 2.6 KB

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