2015-09-22 125 views
-1

我有一個大小爲16384(SourceArray)的字節數組。我想把它分成4個部分,4個字節的數組,大小爲4096.現在SourceArray的每個32位將被分成10位,10位,11位和1位(10 + 10 + 11 + 1 = 32位)。先取10位,再取10位,再取11位,再取1位。
可以說例如來自sourceArray的前4個字節,我得到一個值9856325.現在9856325(dec)= 00000000100101100110010101000101(二進制)--------------------- -------- 0000000010(10位)0101100110(10位)01010100010(11位)1(1位)。我不能在字節數組中存儲10,10,11位,所以我將它存儲到Int16數組中,並且對於1位,我可以將它存儲到一個字節數組中。 ` 我希望問題陳述清楚。我創建了一些邏輯。將32位整數拆分爲4部分

 Int16[] Array1 = new Int16[4096]; 
     Int16[] Array2 = new Int16[4096]; 
     Int16[] Array3 = new Int16[4096]; 
     byte[] Array4 = new byte[4096]; 

     byte[] SourceArray = File.ReadAllBytes(@"Reading an image file from directory"); 
    //Size of source Array = 16384 

     for (int i = 0; i < 4096; i++) 
     { 
      uint temp = BitConverter.ToUInt32(SourceArray, i * 4); 
      uint t = temp; 
      Array1[i] = (Int16)(t >> 22); 
      t = temp << 10; 
      Array2[i] = (Int16)(t >> 22); 
      t = temp << 20; 
      Array3[i] = (Int16)(t >> 21); 
      t = temp << 31; 
      Array4[i] = (byte)(t>>31); 
     } 

但我沒有得到實際結果。我可能會錯過我的邏輯。請驗證它,最新的錯誤或者如果你有更好的邏輯,請給我建議。

+0

有一些類型,可以幫助你,首先是'System.Collections.BitArray':https://msdn.microsoft.com/en-us/library/system.collections.bitarray(v=vs.110).aspx,另一個是'System.Collections .Specialized.BitVector32' https://msdn.microsoft.com/zh-cn/library/system.collections.specialized.bitvector32(v=vs.110).aspx –

+0

Split到10,10,11,1你正在將一個4字節的值(int32)分解爲一個7字節的值,不是嗎? IOW它不應該是4096,而是16384作爲數組大小。 –

+0

不,我把它分成4個字節的數組,大小爲4096.這是4096 * 4 = 16384字節 – Bicky

回答

0

在我看來更容易處理來自最後(最低顯著位)起始位:

uint t = BitConverter.ToUInt32(SourceArray, i * 4); 
Array4[i] = (byte) (t & 0x1); 
t >>= 1; 
Array3[i] = (Int16) (t & 0x7ff); // 0x7ff - mask for 11 bits 
t >>= 11; 
Array2[i] = (Int16) (t & 0x3ff); // 0x3ff - mask for 10 bits 
t >>= 10; 
Array1[i] = (Int16) t; // we don't need mask here 

還是在位組的順序相反:

uint t = BitConverter.ToUInt32(SourceArray, i * 4); 
Array2[i] = (Int16) (t & 0x3ff); // 0x3ff - mask for 10 bits 
t >>= 10; 
Array2[i] = (Int16) (t & 0x3ff); // 0x3ff - mask for 10 bits 
t >>= 10; 
Array3[i] = (Int16) (t & 0x7ff); // 0x7ff - mask for 11 bits 
t >>= 11; 
Array4[i] = (byte) (t & 0x1); // we don't need mask here 
+0

你怎麼計算掩碼的位? – Bicky

+0

在我心中。這是基礎知識。閱讀[wiki](https://en.wikipedia.org/wiki/Mask_(computing))。 – Dmitry

+0

@Jubatian Huh,固定。謝謝。 – Dmitry