将2个连续字节转换为一个int值在C#中提高速度

本文关键字:值在 int 一个 高速度 字节 连续 2个 转换 | 更新日期: 2023-09-27 18:21:39

我需要将两个字节合并为一个int值。

我从我的相机收到一个16位的图像,两个连续的字节具有一个像素的强度值。我的目标是将这两个字节组合成一个"int"值。

我设法使用以下代码做到这一点:

for (int i = 0; i < VectorLength * 2; i = i + 2)
{
  NewImageVector[ImagePointer] = ((int)(buffer.Array[i + 1]) << 8) | ((int)(buffer.Array[i]));      
  ImagePointer++;
}

我的图像是1280*960,因此VectorLength==1228800,而输入缓冲区大小是2*1228800=2457600个元素。。。

有什么办法让我加快速度吗?也许还有另一种方法,所以我不需要使用for循环。

感谢

将2个连续字节转换为一个int值在C#中提高速度

您可以使用等价于c的并集。我不确定是否更快,但更优雅:

[StructLayout(LayoutKind.Explicit)]
struct byte_array
{
  [FieldOffset(0)]
  public byte byte1;
  [FieldOffset(1)]
  public byte byte2;
  [FieldOffset(0)]
  public short int0;
}

这样使用:

byte_array ba = new byte_array();
//insert the two bytes
ba.byte1 = (byte)(buffer.Array[i]);
ba.byte2 = (byte)(buffer.Array[i + 1]);
//get the integer
NewImageVector[ImagePointer] = ba.int1;

您可以填充两个字节并使用int。要找到更快的方法,请使用StopWatch类并比较以下两种方法:

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//The code
stopWatch.Stop();
MessageBox.Show(stopWatch.ElapsedTicks.ToString()); //Or milliseconds ,...

假设您可以(重新)将NewImageVector定义为short[],并且Buffer中的每两个连续字节都应该转换为short(这基本上就是您现在正在做的,只有您之后转换为int),那么您可以使用Buffer.BlockCopy来为您做这件事。

正如文档告诉的那样,Buffer.BlockCopy将字节从一个数组复制到另一个数组,因此为了在缓冲区中复制字节,您需要执行以下操作:

Buffer.BlockCopy(Buffer, 0, NewImageVector, 0, [NumberOfExpectedShorts] * 2)

此消息将告诉BlockCopy,您要开始从索引0开始的Buffer向索引0起始的NewImageVector复制字节,并且您要复制[NumberOfExpectedShorts] * 2字节(因为每个短为两个字节长)。

没有循环,但它确实取决于使用short[]数组而不是int[]数组的能力(实际上,也取决于从使用数组开始)。

注意,这也要求Buffer中的字节按little-endian的顺序排列(即Buffer[index]包含低字节,buffer[index + 1]包含高字节)。

通过使用不安全的指针来迭代数组,可以实现小幅的性能提升。以下代码假设source是输入字节数组(在您的情况下为buffer.Array)。它还假设CCD_ 19具有偶数个元素。在生产代码中,您显然必须检查这些内容。

int[] output = new int[source.Length / 2];
fixed (byte* pSource = source)
fixed (int* pDestination = output)
{
    byte* sourceIterator = pSource;
    int* destIterator = pDestination;
    for (int i = 0; i < output.Length; i++)
    {
        (*destIterator) = ((*sourceIterator) | (*(sourceIterator + 1) << 8));
        destIterator++;
        sourceIterator += 2;
    }
}
return output;