2016-01-18 62 views
2

我有三個bytearray有長度。我想合併字節數組1的字節數組索引0,1,然後索引0,1的bytearaay2和索引bytearray3到長度。將3個字節陣列合併爲一個單一的c#

像這樣:

場景:

a1[0]a1[1]a2[0]a2[1]a3[0]a3[1]a1[2]a1[3]a2[2]a2[3]a3[2]a3[3] ... 

and then so on up to 40000. 

所以最後我想3字節數組合併到單獨一個爲一對分組。

+1

一個非常簡單的循環有什麼問題? –

回答

2

提供所有的數組(比方說,source1source2source3)是相同長度的這個長度是甚至號碼40000):

Byte[] result = new Byte[source1.Length * 3]; 

    for (int i = 0; i < source1.Length/2; ++i) { 
    result[i * 6] = source1[2 * i]; 
    result[i * 6 + 1] = source1[2 * i + 1]; 

    result[i * 6 + 2] = source2[2 * i]; 
    result[i * 6 + 3] = source2[2 * i + 1]; 

    result[i * 6 + 4] = source3[2 * i]; 
    result[i * 6 + 5] = source3[2 * i + 1]; 
    } 

只是for循環

0

C#3.0可以使用LINQ

Byte[] combinedByte = bytearray1.Concat(bytearray2).ToArray(); 
Byte[] combinedByte = combinedByte.Concat(bytearray3).ToArray(); 
+0

他希望數組值交織非連接 –

+0

實際上它連接了bytearray1和bytearray2。所以排序是bytearray1(來自byteaaray1的所有字節),然後是bytearray2(來自bytearray2的所有字節)。但是我想bytearray1 [0] bytearray1 [1] bytearray2 [0] bytearray2 [1],然後依此類推。 在對兩個0,1索引2,3索引和4,5等全部三個字節數組中。 –

+0

我編輯我的帖子......用這種方法合併3個字節的數組到單個 – rdn87

2
int resultIndex = 0; 
int groupingIndex = 0; 
int maxLength = 40000; 
while (resultIndex < maxLength) 
{ 
    result[resultIndex] = source1[groupingIndex]; 
    resultIndex++; 
    if (resultIndex >= maxLength) break; 
    result[resultIndex] = source1[groupingIndex+1]; 
    resultIndex++; 
    if (resultIndex >= maxLength) break; 
    result[resultIndex] = source2[groupingIndex]; 
    resultIndex++; 
    if (resultIndex >= maxLength) break; 
    result[resultIndex] = source2[groupingIndex+1]; 
    resultIndex++; 
    if (resultIndex >= maxLength) break; 
    result[resultIndex] = source3[groupingIndex]; 
    resultIndex++; 
    if (resultIndex >= maxLength) break; 
    result[resultIndex] = source3[groupingIndex+1]; 
    resultIndex++; 
    if (resultIndex >= maxLength) break; 
    groupingIndex = groupIndex + 2; 
} 

你很明顯可以使用一些輔助函數來解決這個問題。如果您允許結果初始爲源長度大小的3倍,那麼您也可以簡化循環(取消if檢查),然後在交錯後修剪到適當的大小。