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 Array.Reverse(source);
34 public static byte[] LEBytes(uint[] values)
36 byte[] result = new byte[values.Length * sizeof(uint)];
37 Buffer.BlockCopy(values, 0, result, 0, result.Length);
42 public static uint[] ToUInt32Array(byte[] bytes)
44 uint[] result = new uint[bytes.Length / sizeof(uint)];
45 Buffer.BlockCopy(bytes, 0, result, 0, bytes.Length);
50 public static byte[] BEBytes(ushort n)
52 byte[] resultBytes = BitConverter.GetBytes(n);
54 Array.Reverse(resultBytes);
59 public static byte[] BEBytes(uint n)
61 byte[] resultBytes = BitConverter.GetBytes(n);
63 Array.Reverse(resultBytes);
68 public static byte[] BEBytes(ulong n)
70 byte[] resultBytes = BitConverter.GetBytes(n);
72 Array.Reverse(resultBytes);
78 public static ushort BEBytesToUInt16(byte[] bytes)
80 if (bytes.Length != sizeof(ushort))
82 throw new InteropException("Array size doesn't match the ushort data type.");
87 return BitConverter.ToUInt16(bytes, 0);
90 public static uint BEBytesToUInt32(byte[] bytes)
92 if (bytes.Length != sizeof(uint))
94 throw new InteropException("Array size doesn't match the uint data type.");
99 return BitConverter.ToUInt32(bytes, 0);
102 public static ulong BEBytesToUInt64(byte[] bytes)
104 if (bytes.Length != sizeof(ulong))
106 throw new InteropException("Array size doesn't match the ulong data type.");
109 Array.Reverse(bytes);
111 return BitConverter.ToUInt64(bytes, 0);
114 public static IEnumerable<byte> ParseHex(string hex)
116 return Enumerable.Range(0, hex.Length)
117 .Where(x => x % 2 == 0)
118 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16));
121 public static string ToHex(IEnumerable<byte> bytes)
123 StringBuilder sb = new StringBuilder();
124 foreach (byte b in bytes)
126 sb.AppendFormat("{0:x2}", b);
128 return sb.ToString();