我有以下我试图理解的代码。
Big Integer 类(自定义,而非标准类)具有以下成员:
private const int maxLength = 2000;
private uint[] data = null; // stores bytes from the Big Integer
public int dataLength; // number of actual chars used
构造函数如下:
public BigInteger(long value)
{
data = new uint[maxLength];
long tempVal = value;
// copy bytes from long to BigInteger without any assumption of
// the length of the long datatype
dataLength = 0;
while(value != 0 && dataLength < maxLength)
{
data[dataLength] = (uint)(value & 0xFFFFFFFF);
value >>= 32;
dataLength++;
}
if(tempVal > 0) // overflow check for +ve value
{
if(value != 0 || (data[maxLength-1] & 0x80000000) != 0)
throw(new ArithmeticException("Positive overflow in constructor."));
}
else if(tempVal < 0) // underflow check for -ve value
{
if(value != -1 || (data[dataLength-1] & 0x80000000) == 0)
throw(new ArithmeticException("Negative underflow in constructor."));
}
本质上,BigInteger 类有助于处理大整数。构造函数用于将 long 值分配给 Big Integer 对象。我知道名为 value 的变量被复制到 uint[] 数据数组(允许的最大位数为 maxLength)。
我无法完全理解如何检查下溢和上溢。我了解条件 if(tempVal > 0) 和 else if(tempVal < 0) 但为什么在下溢和上溢的情况下数据的最高数组索引与 0x80000000 相加?(为什么在上溢/下溢的情况下不为0xFFFFFFFF?如果数字比允许的最大数量多/少1,则会导致上溢/下溢)
此外,将 long 值传递给构造函数是否会限制 BigInteger 的整体大小(其最大值可以与 long 变量的最大值相同)?