我需要将两个字节合并成一个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-循环。
谢谢
发布于 2015-11-11 12:41:00
假设您可以(重新)将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]包含高字节)。
发布于 2015-11-11 12:05:34
您可以使用与c. m的并行不悖的方法,我不确定是否更快,但更优雅:
[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 = new Stopwatch();
stopWatch.Start();
//The code
stopWatch.Stop();
MessageBox.Show(stopWatch.ElapsedTicks.ToString()); //Or milliseconds ,...发布于 2015-11-11 12:24:16
您可以通过使用不安全的指针来迭代数组来实现较小的性能提高。下面的代码假设source是输入字节数组(在您的例子中是buffer.Array)。它还假设source有偶数的元素。在生产代码中,您显然需要检查这些内容。
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;https://stackoverflow.com/questions/33650063
复制相似问题