簡體   English   中英

C#增加字節數組用作整數計數器的最快方法?

[英]C# Fastest way to increment a byte array used as an integer counter?

我在並行CTR實現(加密)中使用分段整數計數器(字節數組)。 需要將計數器的大小增加到與每個處理器正在處理的數據塊相對應的大小。 因此,該數字需要增加一個以上的位值。 換句話說..字節數組起着大整數的作用,我需要將字節數組的和值增加一個整數倍。 我目前正在使用以下所示的使用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自己的加密貨幣專門創建的。

我使用了Cory Nelsons答案的一種變體,以正確的字節序創建數組並返回一個新數組。 這比最初發布的方法要快很多。.感謝您的幫助。

private byte[] Increase(byte[] Counter, int Count)
{
    int carry = 0;
    byte[] buffer = new byte[Counter.Length];
    int offset = buffer.Length - 1;
    byte[] cnt = BitConverter.GetBytes(Count);
    byte osrc, odst, ndst;

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

    for (int i = offset; i > 0; i--)
    {
        odst = buffer[i];
        osrc = offset - i < cnt.Length ? cnt[offset - i] : (byte)0;
        ndst = (byte)(odst + osrc + carry);
        carry = ndst < odst ? 1 : 0;
        buffer[i] = ndst;
    }

    return buffer;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM