2 * Novacoin classes library
3 * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 using System.Collections.Generic;
26 public class InteropException : Exception
28 public InteropException()
32 public InteropException(string message)
37 public InteropException(string message, Exception inner)
38 : base(message, inner)
45 public static byte[] ReverseBytes(byte[] source)
47 byte[] b = new byte[source.Length];
56 public static byte[] LEBytes(uint[] values)
58 byte[] result = new byte[values.Length * sizeof(uint)];
59 Buffer.BlockCopy(values, 0, result, 0, result.Length);
64 public static uint[] ToUInt32Array(byte[] bytes)
66 uint[] result = new uint[bytes.Length / sizeof(uint)];
67 Buffer.BlockCopy(bytes, 0, result, 0, bytes.Length);
72 public static byte[] BEBytes(ushort n)
74 byte[] resultBytes = BitConverter.GetBytes(n);
76 Array.Reverse(resultBytes);
81 public static byte[] BEBytes(uint n)
83 byte[] resultBytes = BitConverter.GetBytes(n);
85 Array.Reverse(resultBytes);
90 public static byte[] BEBytes(ulong n)
92 byte[] resultBytes = BitConverter.GetBytes(n);
94 Array.Reverse(resultBytes);
100 public static ushort BEBytesToUInt16(byte[] bytes)
102 if (bytes.Length != sizeof(ushort))
104 throw new InteropException("Array size doesn't match the ushort data type.");
107 Array.Reverse(bytes);
109 return BitConverter.ToUInt16(bytes, 0);
112 public static uint BEBytesToUInt32(byte[] bytes)
114 if (bytes.Length != sizeof(uint))
116 throw new InteropException("Array size doesn't match the uint data type.");
119 Array.Reverse(bytes);
121 return BitConverter.ToUInt32(bytes, 0);
124 public static ulong BEBytesToUInt64(byte[] bytes)
126 if (bytes.Length != sizeof(ulong))
128 throw new InteropException("Array size doesn't match the ulong data type.");
131 Array.Reverse(bytes);
133 return BitConverter.ToUInt64(bytes, 0);
136 public static IEnumerable<byte> HexToEnumerable(string hex)
138 return Enumerable.Range(0, hex.Length)
139 .Where(x => x % 2 == 0)
140 .Select(x => Convert.ToByte(hex.Substring(x, 2), 16));
143 public static IList<byte> HexToList(string hex)
145 return HexToEnumerable(hex).ToList();
148 public static string ToHex(IEnumerable<byte> bytes)
150 StringBuilder sb = new StringBuilder();
151 foreach (byte b in bytes)
153 sb.AppendFormat("{0:x2}", b);
155 return sb.ToString();