public static byte[] ToByteArrayUnsigned(this FastInteger i, bool bigEndian) { byte[] bytes = i.ToByteArray(); int length = bytes.Length; while (length > 1 && ((bytes[length - 1] == 0 && bytes[length - 2] < 128) || (bytes[length - 1] == 255 && bytes[length - 2] >= 128))) { length--; } Array.Resize(ref bytes, length); if (bigEndian) { Array.Reverse(bytes, 0, bytes.Length); } return(bytes); }
public static bool UnitTest() { Random random = new Random(1001); for (int i = 10000; --i >= 0;) { byte[] bytes1 = new byte[31 + random.Next(2)]; byte[] bytes2 = new byte[31 + random.Next(2)]; random.NextBytes(bytes1); random.NextBytes(bytes2); BigInteger n1 = new BigInteger(bytes1); BigInteger n2 = new BigInteger(bytes2); FastInteger f1 = new FastInteger(bytes1); FastInteger f2 = new FastInteger(bytes2); if (n1.ToString() != f1.ToString()) { System.Diagnostics.Debugger.Break(); } if (n2.ToString() != f2.ToString()) { System.Diagnostics.Debugger.Break(); } BigInteger a1 = n1 + n2; FastInteger a2 = f1 + f2; if (a1.ToString() != a2.ToString()) { var by1 = a1.ToByteArray(); var by2 = a2.ToByteArray(); System.Diagnostics.Debugger.Break(); } BigInteger s1 = n1 - n2; FastInteger s2 = f1 - f2; if (s1.ToString() != s2.ToString()) { var by1 = s1.ToByteArray(); var by2 = s2.ToByteArray(); System.Diagnostics.Debugger.Break(); } BigInteger m1 = n1 * n2; FastInteger m2 = f1 * f2; if (m1.ToString() != m2.ToString()) { System.Diagnostics.Debugger.Break(); } int shrvalue = random.Next(256) + 1; BigInteger sh1 = n1 >> shrvalue; FastInteger sh2 = f1 >> shrvalue; if (sh1.ToString() != sh2.ToString()) { System.Diagnostics.Debugger.Break(); } if ((-f1).ToString() != (-n1).ToString() || (-f2).ToString() != (-n2).ToString()) { System.Diagnostics.Debugger.Break(); } int shlvalue = random.Next(256) + 1; BigInteger shl1 = n1 << shlvalue; FastInteger shl2 = f1 << shlvalue; if (shl1.ToString() != shl2.ToString()) { System.Diagnostics.Debugger.Break(); } BigInteger and1 = n1 & n2; FastInteger and2 = f1 & f2; if (and1.ToString() != and2.ToString()) { System.Diagnostics.Debugger.Break(); } BigInteger xor1 = n1 ^ n2; FastInteger xor2 = f1 ^ f2; if (xor1.ToString() != xor2.ToString()) { System.Diagnostics.Debugger.Break(); } } return(true); }