我的代码中最慢的部分是我使用Bouncy Castle的“BigInteger.Multiply()”方法。为了尝试加快速度,我试图插入下面的代码,看看是否有任何改进。
我知道我做的不对,因为当Bouncy Castle看到我发送给它的BigInteger时,我会遇到很多错误和异常:
if (this.sign != 1 || val.sign != 1)
{
//todo: test encoding, twos compliment
}
var tempThis = this.ToByteArrayUnsigned();
Array.Reverse(tempThis);
System.Numerics.BigInteger aThis = new System.Numerics.BigInteger(tempThis);
var tempThat = val.ToByteArrayUnsigned();
Array.Reverse(tempThat);
System.Numerics.BigInteger bThat = new System.Numerics.BigInteger(tempThat);
var msResult = System.Numerics.BigInteger.Multiply(aThis, bThat);
var tmpRet = msResult.ToByteArray();
Array.Reverse(tmpRet);
var ret = new BigInteger(tmpRet);
return ret;
这是原始BC功能
public BigInteger Multiply( BigInteger val)
{
// THEORY: If I use the native System.Numerics here, then I might get better performance
if (val == this)
return Square();
if ((sign & val.sign) == 0)
return Zero;
if (val.QuickPow2Check()) // val is power of two
{
BigInteger result = this.ShiftLeft(val.Abs().BitLength - 1);
return val.sign > 0 ? result : result.Negate();
}
if (this.QuickPow2Check()) // this is power of two
{
BigInteger result = val.ShiftLeft(this.Abs().BitLength - 1);
return this.sign > 0 ? result : result.Negate();
}
int resLength = magnitude.Length + val.magnitude.Length;
int[] res = new int[resLength];
Multiply(res, this.magnitude, val.magnitude);
int resSign = sign ^ val.sign ^ 1;
return new BigInteger(resSign, res, true);
}