{"id":266,"date":"2020-12-09T15:22:05","date_gmt":"2020-12-09T15:22:05","guid":{"rendered":"https:\/\/michaeljohnsteiner.com\/?p=266"},"modified":"2020-12-09T15:22:05","modified_gmt":"2020-12-09T15:22:05","slug":"bigintegerhelper-cs","status":"publish","type":"post","link":"https:\/\/michaeljohnsteiner.com\/index.php\/2020\/12\/09\/bigintegerhelper-cs\/","title":{"rendered":"BigIntegerHelper.cs"},"content":{"rendered":"\n<p>BigInteger Helper Class<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\nusing System.Text;\npublic static class BigIntegerHelper\n{\n    private static readonly BigInteger Ten   = new BigInteger(10);\n    private static readonly BigInteger Three = new BigInteger(3);\n    private static readonly BigInteger ONE   = new BigInteger(1);\n    private static readonly BigInteger Two   = new BigInteger(2);\n    public static BigInteger BigIntegerBase2(this string binaryValue)\n    {\n        BigInteger res = 0;\n        if (binaryValue.Count(b => b == '1') + binaryValue.Count(b => b == '0') != binaryValue.Length) return res;\n        foreach (var c in binaryValue)\n        {\n            res &lt;&lt;= 1;\n            res +=  c == '1' ? 1 : 0;\n        }\n        return res;\n    }\n    public static BigInteger BigIntegerBase16(this string hexNumber)\n    {\n        if (string.IsNullOrEmpty(hexNumber))\n            throw new Exception(\"Error: hexNumber cannot be either null or have a length of zero.\");\n        if (!hexNumber.ContainsOnly(\"0123456789abcdefABCDEFxX\"))\n            throw new Exception(\"Error: hexNumber cannot contain characters other than 0-9,a-f,A-F, or xX\");\n        hexNumber = hexNumber.ToUpper();\n        if (hexNumber.IndexOf(\"0X\", StringComparison.OrdinalIgnoreCase) != -1)\n            hexNumber = hexNumber.Substring(2);\n        var bytes = Enumerable.Range(0, hexNumber.Length)\n            .Where(x => x % 2 == 0)\n            .Select(x => Convert.ToByte(hexNumber.Substring(x, 2), 16))\n            .ToArray();\n        return new BigInteger(bytes.Concat(new byte[] {0}).ToArray());\n    }\n    public static BigInteger BigIntegerBase10(this string str)\n    {\n        var number = new BigInteger();\n        int i;\n        for (i = 0; i &lt; str.Length; i++)\n            if (str[i] >= '0' &amp;&amp; str[i] &lt;= '9')\n                number = number * Ten + long.Parse(str[i].ToString());\n        return number;\n    }\n    private static byte[] HexToByteArray(this string hex)\n    {\n        return Enumerable.Range(0, hex.Length)\n            .Where(x => x % 2 == 0)\n            .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))\n            .ToArray();\n    }\n    public static BigInteger ToBigInteger(this char ul)\n    {\n        return new BigInteger(ul);\n    }\n    public static BigInteger ToBigInteger(this byte ul)\n    {\n        return new BigInteger(ul);\n    }\n    public static BigInteger ToBigInteger(this sbyte ul)\n    {\n        return new BigInteger(ul);\n    }\n    public static BigInteger ToBigInteger(this short ul)\n    {\n        return new BigInteger(ul);\n    }\n    public static BigInteger ToBigInteger(this ushort ul)\n    {\n        return new BigInteger(ul);\n    }\n    public static BigInteger ToBigInteger(this int ul)\n    {\n        return new BigInteger((ulong) ul);\n    }\n    public static BigInteger ToBigInteger(this uint ul)\n    {\n        return new BigInteger((ulong) ul);\n    }\n    public static BigInteger ToBigInteger(this long ul)\n    {\n        return new BigInteger((ulong) ul);\n    }\n    public static BigInteger ToBigInteger(this ulong ul)\n    {\n        return new BigInteger(ul);\n    }\n    public static BigInteger ModPow(this BigInteger n, BigInteger e, BigInteger m)\n    {\n        var s = ONE;\n        var u = e;\n        while (!u.IsZero)\n        {\n            if ((u &amp; ONE) == 1)\n                s = s * n % m;\n            u >>= 1;\n            n =   n * n % m;\n        }\n        return s;\n    }\n    public static double ConfidenceToProbability(int confidence)\n    {\n        var a = Two.Pow(confidence);\n        var b = 100.0 \/ (double) a;\n        var c = 100.0 - b;\n        return c;\n    }\n    public static BigInteger Pow(this BigInteger n, BigInteger exp)\n    {\n        var y = ONE;\n        var z = n;\n        while (exp != 0)\n        {\n            if ((exp &amp; 0x1) == 1)\n                y *= z;\n            exp >>= 1;\n            if (exp != 0)\n                z *= z;\n        }\n        return y;\n    }\n    public static List&lt;BigInteger> GetFactors(this BigInteger n)\n    {\n        var Factors = new List&lt;BigInteger>();\n        var s       = n.Sqrt();\n        var a       = Three;\n        while (a &lt; s)\n        {\n            if (n % a == 0)\n            {\n                Factors.Add(a);\n                if (a * a != n)\n                    Factors.Add(n \/ a);\n            }\n            a += 2;\n        }\n        return Factors;\n    }\n    public static BigInteger Gcd(this BigInteger a, BigInteger b)\n    {\n        while (b > BigInteger.Zero)\n        {\n            var r = a % b;\n            a = b;\n            b = r;\n        }\n        return a;\n    }\n    public static BigInteger Lcm(this BigInteger a, BigInteger b)\n    {\n        return a * b \/ a.Gcd(b);\n    }\n    public static BigInteger BigIntegerBase2(this BigInteger bi, string binaryValue)\n    {\n        bi = BigInteger.Zero;\n        if (binaryValue.Count(b => b == '1') + binaryValue.Count(b => b == '0') != binaryValue.Length)\n            return bi;\n        foreach (var c in binaryValue)\n        {\n            bi &lt;&lt;= 1;\n            bi +=  c == '1' ? 1 : 0;\n        }\n        return bi;\n    }\n    public static int GetByteWidth(this BigInteger n)\n    {\n        return GetBitWidth(n) >> 3;\n    }\n    public static int GetBitWidth(this BigInteger n)\n    {\n        BigInteger bitWidth = 1;\n        var        v        = n;\n        while ((v >>= 1) > 0)\n            bitWidth++;\n        if (bitWidth &lt; 8)\n            bitWidth = 8;\n        return (int) bitWidth;\n    }\n    public static BigInteger GetMaxValue(this BigInteger bi, int bitLength)\n    {\n        if (bi.Sign == -1)\n            bitLength -= 1;\n        return BigInteger.One &lt;&lt; bitLength;\n    }\n    public static BigInteger GetMaxValue(this BigInteger bi)\n    {\n        var bitLength = bi.GetBitWidth();\n        if (bi.Sign == -1)\n            bitLength -= 1;\n        return (BigInteger.One &lt;&lt; bitLength) - BigInteger.One;\n    }\n    public static BigInteger GetMaxValueBitWidth(int bitLength)\n    {\n        return (BigInteger.One &lt;&lt; bitLength) - BigInteger.One;\n    }\n    public static BigInteger BigIntegerBase16(this BigInteger bi, string hexNumber)\n    {\n        if (string.IsNullOrEmpty(hexNumber))\n            throw new Exception(\"Error: hexNumber cannot be either null or have a length of zero.\");\n        if (!hexNumber.ContainsOnly(\"0123456789abcdefABCDEFxX\"))\n            throw new Exception(\"Error: hexNumber cannot contain characters other than 0-9,a-f,A-F, or xX\");\n        hexNumber = hexNumber.ToUpper();\n        if (hexNumber.IndexOf(\"0X\", StringComparison.OrdinalIgnoreCase) != -1)\n            hexNumber = hexNumber.Substring(2);\n        var bytes = Enumerable.Range(0, hexNumber.Length)\n            .Where(x => x % 2 == 0)\n            .Select(x => Convert.ToByte(hexNumber.Substring(x, 2), 16))\n            .ToArray();\n        return new BigInteger(bytes.Concat(new byte[] {0}).ToArray());\n    }\n    public static BigInteger BigIntegerBase10(this BigInteger bi, string str)\n    {\n        if (str[0] == '-' || str.IndexOf('.') != -1)\n            throw new Exception($\"Invalid numeric string. Only positive numbers and whole numbers are allowed. Value={str}\");\n        var number = new BigInteger();\n        int i;\n        for (i = 0; i &lt; str.Length; i++)\n            if (str[i] >= '0' &amp;&amp; str[i] &lt;= '9')\n                number = number * Ten + long.Parse(str[i].ToString());\n        return number;\n    }\n    public static string ToBinaryString(this BigInteger bigint)\n    {\n        var bytes  = bigint.ToByteArray();\n        var index  = bytes.Length - 1;\n        var base2  = new StringBuilder(bytes.Length * 8);\n        var binary = Convert.ToString(bytes[index], 2);\n        if (binary[0] != '0' &amp;&amp; bigint.Sign == 1) base2.Append('0');\n        base2.Append(binary);\n        for (index--; index >= 0; index--)\n            base2.Append(Convert.ToString(bytes[index], 2).PadLeft(8, '0'));\n        return base2.ToString();\n    }\n    public static string ToHexString(this BigInteger bi)\n    {\n        var bytes = bi.ToByteArray();\n        var sb    = new StringBuilder();\n        foreach (var b in bytes)\n        {\n            var hex = b.ToString(\"X2\");\n            sb.Append(hex);\n        }\n        return sb.ToString();\n    }\n    public static string ToOctalString(this BigInteger bigint)\n    {\n        var bytes         = bigint.ToByteArray();\n        var index         = bytes.Length - 1;\n        var base8         = new StringBuilder((bytes.Length \/ 3 + 1) * 8);\n        var rem           = bytes.Length % 3;\n        if (rem == 0) rem = 3;\n        var base0         = 0;\n        while (rem != 0)\n        {\n            base0 &lt;&lt;= 8;\n            base0 +=  bytes[index--];\n            rem--;\n        }\n        var octal = Convert.ToString(base0, 8);\n        if (octal[0] != '0' &amp;&amp; bigint.Sign == 1) base8.Append('0');\n        base8.Append(octal);\n        while (index >= 0)\n        {\n            base0 = (bytes[index] &lt;&lt; 16) + (bytes[index - 1] &lt;&lt; 8) + bytes[index - 2];\n            base8.Append(Convert.ToString(base0, 8).PadLeft(8, '0'));\n            index -= 3;\n        }\n        return base8.ToString();\n    }\n    \/\/\/ &lt;summary>\n    \/\/\/     Approximation\n    \/\/\/ &lt;\/summary>\n    public static BigInteger Sqrt(this BigInteger n)\n    {\n        var q = BigInteger.One &lt;&lt; ((int) BigInteger.Log(n, 2) >> 1);\n        var m = BigInteger.Zero;\n        while (BigInteger.Abs(q - m) >= 1)\n        {\n            m = q;\n            q = (m + n \/ m) >> 1;\n        }\n        return q;\n    }\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>BigInteger Helper Class<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[2],"tags":[14,29,28],"_links":{"self":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts\/266"}],"collection":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/comments?post=266"}],"version-history":[{"count":1,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts\/266\/revisions"}],"predecessor-version":[{"id":267,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/posts\/266\/revisions\/267"}],"wp:attachment":[{"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/media?parent=266"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/categories?post=266"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/michaeljohnsteiner.com\/index.php\/wp-json\/wp\/v2\/tags?post=266"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}