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;
27 /// Encodes unsigned integer value into compact representation.
29 /// See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for additional information.
31 /// <param name="n">Unsigned integer value</param>
32 /// <returns>Byte sequence</returns>
33 public static byte[] EncodeVarInt(ulong n)
35 var resultBytes = new List<byte>();
39 // Values up to 0xfc are stored directly without any prefix
40 resultBytes.Add((byte)n);
47 if (n <= ushort.MaxValue)
51 valueBytes = BitConverter.GetBytes((ushort)n);
53 else if (n <= uint.MaxValue)
57 valueBytes = BitConverter.GetBytes((uint)n);
63 valueBytes = BitConverter.GetBytes(n);
66 resultBytes.Add(prefix);
67 resultBytes.AddRange(valueBytes);
70 return resultBytes.ToArray();
74 /// Encodes integer value into compact representation.
76 /// See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for additional information.
78 /// <param name="n">Integer value</param>
79 /// <returns>Byte sequence</returns>
80 public static byte[] EncodeVarInt(long n)
82 return EncodeVarInt((ulong)n);
85 public static int GetEncodedSize(long n)
91 else if (n <= ushort.MaxValue)
95 else if (n <= uint.MaxValue)
106 /// Decodes integer value from compact representation
108 /// See https://bitcoin.org/en/developer-reference#compactsize-unsigned-integers for additional information.
110 /// <param name="bytes">Byte sequence</param>
111 /// <returns>Integer value</returns>
112 public static ulong DecodeVarInt(byte[] bytes)
114 var prefix = bytes[0];
115 var bytesArray = new byte[bytes.Length - 1];
117 bytes.CopyTo(bytesArray, 1); // Get rid of prefix
121 case 0xfd: // ushort flag
122 return BitConverter.ToUInt16(bytesArray, 0);
123 case 0xfe: // uint flag
124 return BitConverter.ToUInt32(bytesArray, 0);
125 case 0xff: // ulong flag
126 return BitConverter.ToUInt64(bytesArray, 0);