【问题标题】:Best way to create a Bit/Byte array arithmetics class创建位/字节数组算术类的最佳方法
【发布时间】:2014-04-29 07:51:58
【问题描述】:

我目前正在处理非常大的数字,我想用它们进行简单的计算,但我遇到了问题。当我从字节数组创建数字时,甚至 c# BigInteger 也会超时。

字节数组真的非常大,每个最多几 MB。

所以我想我可以创建一个“字节数组计算器”,它需要 2 个数组并加/减它们。

bit[] result = BitArrCalculator.Add(arrA, arrB)
// arrA is 1001 (9)
// arrB is 11 (3)
// then result should be 1100 (12)

因为我有非常大的数字,所以我无法将它们转换为整数然后再转换回来。至少不在 C# 中。如果有其他语言可以做到这一点,我可以更改语言,但我希望有一个可以处理任意数组大小的解决方案。

感觉应该有一个解决方案/库/框架在那里,但我还没有找到它。

所以我的问题: 使用位/字节数组并对它们进行加法/减法的最佳方法是什么,是否有任何工具/库?

【问题讨论】:

  • 听起来像是一个从头开始解决的有趣问题(任何语言)。

标签: arrays math byte bit biginteger


【解决方案1】:

未经测试。

byte[] Add( byte[] one, byte[] two )
{
    byte[] ret = new byte[ Math.Max( one.Length, two.Length ) ];
    int carry = 0;
    for( int i = 0; i < one.Length && i < two.length; ++i )
    {
        int total = (int)one[i] + two[i] + carry;
        if( total > 255 )
        {
            carry = total - 255;
            total = total - carry;
        }
        ret[i] = (byte) total;
    }

    // at most one of these for loops will execute

    for( int j = i; j < one.Length; ++j )
    {
        int total = carry + one[j];
        if( total > 255 )
        {
            carry = total - 255;
            total = total - carry;
        }
        ret[j] = (byte) total;
    }

    for( int j = i; j < two.Length; ++j )
    {
        int total = carry + two[j];
        if( total > 255 )
        {
            carry = total - 255;
            total = total - carry;
        }
        ret[j] = (byte) total;
    }

    if( carry > 0 ) { /* have to add another byte to the array */ }

    return ret;
}

【讨论】:

    【解决方案2】:

    我决定编写自己的类,它可以对两个给定的位数组进行加法和减法。对我来说,在我的项目中使用位比使用字节更有意义。加减法的逻辑用位真的很简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多