X-Git-Url: https://git.novaco.in/?a=blobdiff_plain;f=Novacoin%2Fuint160.cs;h=e12f10b29330f75126f32c138ebd653ee5d0860c;hb=198c3037b62f2c6007dee4c0a8b0fa41e9225c24;hp=be4d9180a4e5542b4c8b9cc19dbb74f44ae3f593;hpb=a1df90fa7b7daf76469bd5e691910c74d92bf802;p=NovacoinLibrary.git diff --git a/Novacoin/uint160.cs b/Novacoin/uint160.cs index be4d918..e12f10b 100644 --- a/Novacoin/uint160.cs +++ b/Novacoin/uint160.cs @@ -18,6 +18,7 @@ using System; using System.Diagnostics.Contracts; +using System.Linq; namespace Novacoin { @@ -212,6 +213,83 @@ namespace Novacoin return result; } + public static uint160 operator *(uint160 a, ulong multiplier) + { + var result = new uint160(); + + ulong c = 0; + uint i = 0; + + do + { + c += a.pn[i] * multiplier; + result.pn[i] = (uint)c; + c >>= 32; + } while (++i < result.nWidth); + + return result; + } + + public static uint160 operator *(uint160 a, uint160 b) + { + if (!a || !b) + { + // Multiplication by zero results with zero. + return 0; + } + else if (b.bits <= 32) + { + if (b.pn[0] == 1) + { + // If right is 1 then return left operand value + return a; + } + + return a * b.pn[0]; + } + else if (a.bits <= 32) + { + if (a.pn[0] == 1) + { + // If left is 1 then return right operand value + return b; + } + + return a * b.pn[0]; + } + + int m = a.bits / 32 + (a.bits % 32 != 0 ? 1 : 0); + int n = b.bits / 32 + (b.bits % 32 != 0 ? 1 : 0); + + uint160 result = new uint160(); + + uint[] left = a.pn.Take(m).ToArray(); + uint[] right = b.pn.Take(n).ToArray(); + + for (int i = 0; i < m; ++i) + { + uint ai = left[i]; + int k = i; + + ulong temp = 0; + for (int j = 0; j < n; ++j) + { + temp = temp + ((ulong)ai) * right[j] + result.pn[k]; + result.pn[k++] = (uint)temp; + temp >>= 32; + } + + while (temp != 0) + { + temp += result.pn[k]; + result.pn[k++] = (uint)temp; + temp >>= 32; + } + } + + return result; + } + public static uint operator %(uint160 a, uint divisor) { ulong r = 0; @@ -227,6 +305,51 @@ namespace Novacoin return (uint)r; } + public static uint160 operator /(uint160 a, uint160 b) + { + if (b.bits <= 32) + { + return a / b.Low32; + } + + uint160 result = new uint160(); + + uint[] quotient; + uint[] remainder_value; + + int m = a.bits / 32 + (a.bits % 32 != 0 ? 1 : 0); + int n = b.bits / 32 + (b.bits % 32 != 0 ? 1 : 0); + + BignumHelper.DivModUnsigned(a.pn.Take(m).ToArray(), b.pn.Take(n).ToArray(), out quotient, out remainder_value); + + quotient.CopyTo(result.pn, 0); + + return result; + } + + public static uint160 operator %(uint160 a, uint160 b) + { + if (b.bits <= 32) + { + return a % b.Low32; + } + + uint160 result = new uint160(); + + uint[] quotient; + uint[] remainder_value; + + int m = a.bits / 32 + (a.bits % 32 != 0 ? 1 : 0); + int n = b.bits / 32 + (b.bits % 32 != 0 ? 1 : 0); + + BignumHelper.DivModUnsigned(a.pn.Take(m).ToArray(), b.pn.Take(n).ToArray(), out quotient, out remainder_value); + + remainder_value.CopyTo(result.pn, 0); + + return result; + + } + #endregion #region Shift