您正在寻找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
s (的第二个和第四个参数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;
}