2 using System.Collections.Generic;
8 public class InteropException : Exception
10 public InteropException()
14 public InteropException(string message)
19 public InteropException(string message, Exception inner)
20 : base(message, inner)
27 public static byte[] ReverseBytes(byte[] source)
29 byte[] b = new byte[source.Length];
38 public static byte[] LEBytes(uint[] values)
40 byte[] result = new byte[values.Length * sizeof(uint)];
41 Buffer.BlockCopy(values, 0, result, 0, result.Length);
46 public static uint[] ToUInt32Array(byte[] bytes)
48 uint[] result = new uint[bytes.Length / sizeof(uint)];
49 Buffer.BlockCopy(bytes, 0, result, 0, bytes.Length);
54 public static byte[] BEBytes(ushort n)
56 byte[] resultBytes = BitConverter.GetBytes(n);
58 Array.Reverse(resultBytes);
63 public static byte[] BEBytes(uint n)
65 byte[] resultBytes = BitConverter.GetBytes(n);
67 Array.Reverse(resultBytes);
72 public static byte[] BEBytes(ulong n)
74 byte[] resultBytes = BitConverter.GetBytes(n);
76 Array.Reverse(resultBytes);
82 public static ushort BEBytesToUInt16(byte[] bytes)
84 if (bytes.Length != sizeof(ushort))
86 throw new InteropException("Array size doesn't match the ushort data type.");
91 return BitConverter.ToUInt16(bytes, 0);
94 public static uint BEBytesToUInt32(byte[] bytes)
96 if (bytes.Length != sizeof(uint))
98 throw new InteropException("Array size doesn't match the uint data type.");
101 Array.Reverse(bytes);
103 return BitConverter.ToUInt32(bytes, 0);
106 public static ulong BEBytesToUInt64(byte[] bytes)
108 if (bytes.Length != sizeof(ulong))
110 throw new InteropException("Array size doesn't match the ulong data type.");
113 Array.Reverse(bytes);
115 return BitConverter.ToUInt64(bytes, 0);
118 public static IEnumerable<byte> HexToEnumerable(string hex)
120 return Enumerable.Range(0, hex.Length)
121 .Where(x => x % 2 == 0)
122 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16));
125 public static IList<byte> HexToList(string hex)
127 return HexToEnumerable(hex).ToList();
130 public static string ToHex(IEnumerable<byte> bytes)
132 StringBuilder sb = new StringBuilder();
133 foreach (byte b in bytes)
135 sb.AppendFormat("{0:x2}", b);
137 return sb.ToString();