簡體   English   中英

將 ushort 數組轉換為位數組

[英]Convert ushort array to bit array

我有一個 ushort 數組:

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

我如何將其轉換為位數組。 在上面的例子中,一個長度為5 * 16位的數組? 提前致謝!

非常簡單的谷歌搜索給出了這個BitArray 類

例子

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
            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();
            }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM