C# 递增用作整数计数器的字节数组的最快方法?

标签 c# arrays

我在并行 CTR 实现(加密)中使用分段整数计数器(字节数组)。计数器的大小需要与每个处理器正在处理的数据 block 相对应地递增。因此,该数字需要增加一个以上的位值。换句话说..字节数组充当大整数,我需要将字节数组的总和值增加一个整数因子。 我目前正在使用下面显示的使用 while 循环的方法,但我想知道是否有一个明智的方法(& | ^ 等),因为使用循环似乎非常浪费..有什么想法吗?

private void Increment(byte[] Counter)
{
    int j = Counter.Length;
    while (--j >= 0 && ++Counter[j] == 0) { }
}

/// <summary>
/// Increase a byte array by a numerical value
/// </summary>
/// <param name="Counter">Original byte array</param>
/// <param name="Count">Number to increase by</param>
/// <returns>Array with increased value [byte[]]</returns>
private byte[] Increase(byte[] Counter, Int32 Count)
{
    byte[] buffer = new byte[Counter.Length];

    Buffer.BlockCopy(Counter, 0, buffer, 0, Counter.Length);

    for (int i = 0; i < Count; i++)
        Increment(buffer);

    return buffer;
}

最佳答案

标准 O(n) 多精度加法如下(假设 [0] 是 LSB):

static void Add(byte[] dst, byte[] src)
{
    int carry = 0;

    for (int i = 0; i < dst.Length; ++i)
    {
        byte odst = dst[i];
        byte osrc = i < src.Length ? src[i] : (byte)0;

        byte ndst = (byte)(odst + osrc + carry);

        dst[i] = ndst;
        carry = ndst < odst ? 1 : 0;
    }
}

可以帮助我们将其视为小学算术术语,这实际上就是全部内容:

  129
+ 123
-----

还记得,您要从左侧(最低有效数字)开始对每个数字执行加法和进位吗?在这种情况下,每个数字都是数组中的一个字节。

您是否考虑过使用任意精度 BigInteger 而不是自己动手? ?它实际上是专门为 .NET 自己的加密内容创建的。

关于C# 递增用作整数计数器的字节数组的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27389047/

相关文章:

C++将一个数组拆分为2个单独的数组

javascript - JS数组到PHP并使用PDO更新MYSQL中的表

c# webclient 从ssl上传和下载数据

c# - 从 httprequest C# 读取客户端证书

c# - Azure Function V1 构建问题

c# - 我是否需要处理来自 Request.CreateResponse() 的 HttpResponseException?

c++ - 为什么 C++ 函数可以创建可变长度的数组?

c# - 将委托(delegate)传递给事件 c#

python - 删除数组中长度为 1 的维度

c - C中两个数组相加