您正在寻找BlockCopy
:
https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy(v=vs.110).aspx
,是的,short
以及ushort
为2个字节;这就是为什么相应的byte
阵列应该是初始short
之一的两倍。
直接(byte
到short
):
byte[] source = new byte[] { 5, 6 };
short[] target = new short[source.Length/2];
Buffer.BlockCopy(source, 0, target, 0, source.Length);
反向:
short[] source = new short[] {7, 8};
byte[] target = new byte[source.Length * 2];
Buffer.BlockCopy(source, 0, target, 0, source.Length * 2);
使用offset
秒(秒和Buffer.BlockCopy
的第四参数)可以具有一维数组是细分(如你所知):
// it's unclear for me what is the "broken down 1d array", so
// let it be an array of array (say 512 lines, each of 424 items)
ushort[][] image = ...;
// data - sum up all the lengths (512 * 424) and * 2 (bytes)
byte[] data = new byte[image.Sum(line => line.Length) * 2];
int offset = 0;
for (int i = 0; i < image.Length; ++i) {
int count = image[i].Length * 2;
Buffer.BlockCopy(image[i], offset, data, offset, count);
offset += count;
}
感谢您的支持。你能否解释一下'{5,6}'和'{7,8}'究竟在做什么?谢谢。 –
@Oliver Jone:'{5,6}'只是*样本值*:'new byte [] {5,6};' - 创建一个包含两个项目的新数组 - '5'和'6'。 –
谢谢你,只是想指出你可能需要使用'Buffer.BlockCopy(image [i],0,data,offset,count);'当做一个多维数组拷贝时(0是每个数组的起始位置数组作为for循环重复) – Snouto