简体   繁体   English

将 ushort 数组转换为位数组

[英]Convert ushort array to bit array

I have a ushort array:我有一个 ushort 数组:

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

How I can convert it to a bit Array.我如何将其转换为位数组。 In the above example, a length of 5 * 16 bit array?在上面的例子中,一个长度为5 * 16位的数组? Thanks in advance!提前致谢!

Pretty simple google search gives this BitArray Class非常简单的谷歌搜索给出了这个BitArray 类

Example例子

using System.Collections;

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

Update:更新:

So I was interested in the problem and decided to complete a working solution.所以我对这个问题很感兴趣,并决定完成一个可行的解决方案。 This is what I'd do to handle shorts.这就是我处理短裤的方法。 One thing though is I'm assuming the bits will still translate given that you aren't trying to re-interperate back (??) and just want to loop through the raw bits?不过有一件事是我假设这些位仍然会转换,因为您没有尝试重新交互(??)并且只想循环遍历原始位?

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

I mocked this up in LinqPad hence the .Dump() statements so do you're own thing for testing.我在 LinqPad 中对此进行了模拟,因此使用了 .Dump() 语句,因此您是自己的测试对象。 You may have to switch around the order and maybe shift the second in each pair...I'll leave that part for you to work out.你可能不得不改变顺序,也许每对中的第二个……我会把那部分留给你解决。 Also if you just have a single value in your source ushort[] you'll get an error so work out the maths to sort that out too..此外,如果您的源 ushort[] 中只有一个值,您将收到一个错误,因此请计算出数学来解决这个问题。

The result of the above is:上面的结果是:

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