您正在尋找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