2017-10-05 100 views
-1

我有一個USHORT陣列:轉換USHORT陣列位陣列

ushort[] testArray = new ushort[]{1, 2, 3, 4, 5}; 

我怎樣才能將其轉換爲位陣列。在上面的例子中,長度爲5 * 16位數組?提前致謝!

+0

你爲什麼寫'5 * 16'位數組?你不知道'int'被包裹在'Int32'上,而不是'Int16',不是嗎? –

+0

對不起,我輸錯了。源數組是'ushort'。 – user8595258

回答

1

很簡單的谷歌搜索給這個BitArray Class

using System.Collections; 

int[] myInts = new int[5] { 6, 7, 8, 9, 10 }; 
BitArray myBA5 = new BitArray(myInts); 

更新:

所以我很感興趣的問題,並決定完成一個有效的解決方案。這是我會做短褲的。有一件事是,我假設這些位仍然會翻譯,因爲您不想重新回到(??)並只想循環訪問原始位?

var shorts = new ushort[] { 5, 1 }; 
var numberOfInts = (int)Math.Ceiling((decimal)shorts.Length/2); 
var theInts = new int[numberOfInts]; 

var shortsPos = 0; 
for (int i = 0; i < numberOfInts; i++) 
{ 
    theInts[i] = shorts[shortsPos + 1]; 
    theInts[i] = theInts[i] | ((int)shorts[shortsPos] << 16); 
    shortsPos =+ 2; 
    //theInts[i].Dump(); 
} 

var bitArr = new BitArray(theInts); 
foreach (var bit in bitArr) 
{ 
    //bit.Dump(); 
} 

我在LinqPad中嘲笑了這一點,因此.Dump()語句,所以你自己的測試。你可能不得不改變順序,也許會改變每一對中的第二個......我會留下那部分讓你解決。此外,如果你只是在你的源USHORT []一個值,你會得到一個錯誤,以便制定出數學整理了這一點太..

上述結果是:

True 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
True 
False 
True 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
False 
+0

對不起,我打錯了。源數組ushort – user8595258

+0

因此ushort是16位。 BitArray採用int(32位)。你需要把這兩個插件混合在一起。將您的目標設置爲第二個ushort的值,並將第一個左邊的16位逐位進行位平移或將它們一起按位移動。如果你有四個,你會有兩個整數,五個你會有三個整數(仍然按位向左移動五分之一,然後按照我所描述的那樣傳遞整數) –

+0

感謝你的支持努力! – user8595258

0
  int[] testArray = new int[] { 1, 2, 3, 4, 5 }; 
      Dictionary<int, int[]> convertData = new Dictionary<int, int[]>(); 

      foreach (int x in testArray) 
      { 
       System.Collections.BitArray b = new System.Collections.BitArray(Convert.ToByte(x)); 
       convertData[x] = b.Cast<bool>().Select(bit => bit ? 1 : 0).ToArray(); 
      }