将数组进行拆分,使用System.Array.Copy
方法进行拆分。
比如,原数组byte[] newData = new byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
,需要拆分成2个5个元素的数组,拆分完成后,两个数组分别为{1,2,3,4,5}
和{6,7,8,9,10}
.
Copy有4个重载方法。个人喜欢用如图这个
byte[] newData = new byte[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
byte[] b = new byte[5];
byte[] c = new byte[5];
System.Array.Copy(newData, 5, c, 0, 5);
System.Array.Copy(newData, 0, b, 0, 5);
执行完成后,b={1,2,3,4,5}
,c={6,7,8,9,10}
经过重写后
/// <summary>
/// 将一个数组拆成另外一个数组
/// </summary>
/// <param name="originbyte">原始数组,被拆分的数组</param>
/// <param name="oringinstartindex">从原始数组第几个元素开始</param>
/// <param name="destbytelength">目标数组的长度</param>
/// <param name="destbytestartindex">目标数组开始的元素序号,默认为0</param>
/// <returns></returns>
public static byte[] SplitByteArray(byte[] originbyte, int oringinstartindex, int destbytelength, int destbytestartindex = 0)
{
byte[] result = new byte[destbytelength];
System.Array.Copy(originbyte, oringinstartindex, result, destbytestartindex , destbytelength);
return result;
}