gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:01:51 26 4
gpt4 key购买 nike

我在并行 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com